LeetCode #82 Remove Duplicates from Sorted List II

Problem

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Examples

1
2
3
4
5
Input: 1->2->3->3->4->4->5
Output: 1->2->5

Input: 1->1->1->2->3
Output: 2->3

Solution

Method:

Time Complexity:

Space Complexity:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def printList(self, head):
while head:
print(head.val, ' ', end='')
head = head.next

def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head

dummy_head = ListNode(float('-inf'))
dummy_head.next = head

prev_valid_ptr = dummy_head
current_ptr = head
detect_ptr = head.next
should_remove = False

while current_ptr and detect_ptr:
if current_ptr.val == detect_ptr.val:
should_remove = True
current_ptr = current_ptr.next
detect_ptr = detect_ptr.next
continue
else:
if should_remove is False:
prev_valid_ptr = prev_valid_ptr.next

should_remove = False
current_ptr = current_ptr.next
detect_ptr = detect_ptr.next

if should_remove is False:
prev_valid_ptr.next = current_ptr
else:
prev_valid_ptr.next = None

return dummy_head.next

# testcase 1 1->1->2->2
# head = ListNode(1)
# head.next = ListNode(1)
# head.next.next = ListNode(2)
# head.next.next.next = ListNode(2)
# Solution().printList((Solution().deleteDuplicates(head)))

# testcase 2 1->2->3->4
# head = ListNode(1)
# head.next = ListNode(2)
# head.next.next = ListNode(3)
# head.next.next.next = ListNode(4)
# Solution().printList((Solution().deleteDuplicates(head)))

Note

Beware of the continuous duplicates