Problem: Remove all duplicates and return the head of the cleaned linked list
Input: root node of a sorted linked list
Output: root node of the cleaned linked list
Example:
1->1->2->2
-> 1-> 2
Clarification:
while loop to advance toward the end of the linked list. None, return None. None, connect it to the given root node, and set pre to the dummy nodeNonepre.next to cur.nextpre to the current nodecur to the next nodedummy.nextclass Solution:
def deleteDuplicates(self, head):
if not head:
return None
# initialize
cur = head
dummy = ListNode(None, cur)
pre = dummy
# remove duplicates
while cur:
if pre.val == cur.val:
pre.next = cur.next
# Advance cursors
else:
pre = cur # NOT moving pre when duplicate
cur = cur.next
# return the new head node
return dummy.next
We should move pre cursor only when pre.val is differnt from cur.val. However, we shouldn't move pre after removing duplicates. If pre were moved to cur and next node were also a duplicate, the link would be broken.
The above solution adopts a one-step-advance approach. An alternative appoach could be to advance directly to the next non-duplicate node. However, I think using a single while loop is safer and easier to control the flow.
original version
while cur:
if pre.val == cur.val:
pre.next = cur.next
# Advance cursors
else:
pre = cur # NOT moving pre when duplicate
cur = cur.next
alternaive version
# traverse a linked list
while cur:
# remove duplciate
while cur and pre.val == cur.val:
cur = cur.next
pre.next = cur
# Advance cursors
if not cur:
break
else:
pre = cur
cur = cur.next
Time Complexity: O(n), where n is the number of nodes in a linked list
Space Complexity: O(1), use three variables and mutate a linked list