卖萌的弱渣

I am stupid, I am hungry.

Remove Duplicates From Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example:

  • Given 1->1->2, return 1->2.
  • Given 1->1->2->3->3, return 1->2->3.

Solution

(Remove-Duplicates-from-Sorted-List.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return head
  newHead = ListNode(0)
        newHead.next = head
        ret = newHead

        newHead = head
        head = head.next

        while head != None:
            if head.val != newHead.val:
                newHead.next = head
                newHead = head
            head = head.next
        newHead.next = None
        return ret
(Remove-Duplicates-from-Sorted-List.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null)
            return head;
        ListNode prev = head;
        ListNode nextNode = prev.next;
        while (nextNode != null){
            while (nextNode != null && nextNode.val == prev.val)
                nextNode = nextNode.next;
            prev.next = nextNode;
            prev = prev.next;
        }
        return head;
    }
}