82. Remove Duplicates from Sorted List II
Problem
The linked list is sorted. Delete every node whose value appears more than once, leaving only values that were unique, and return the head.
Example: 1→2→3→3→4→4→5 → 1→2→5; 1→1→1→2→3 → 2→3
Remove every value that repeats. With a dummy, prev points to the last kept node; if the run starting at prev.next has length > 1, skip the whole run.
Complexity: O(n).
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = prev = ListNode(0, head)
while prev.next:
cur = prev.next
if cur.next and cur.next.val == cur.val:
while cur.next and cur.next.val == cur.val:
cur = cur.next
prev.next = cur.next # drop the whole run
else:
prev = cur
return dummy.next
assert list_vals(Solution().deleteDuplicates(make_list([1, 2, 3, 3, 4, 4, 5]))) == [1, 2, 5]
assert list_vals(Solution().deleteDuplicates(make_list([1, 1, 1, 2, 3]))) == [2, 3]
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0, head), prev = dummy;
while (prev.next != null) {
ListNode cur = prev.next;
if (cur.next != null && cur.next.val == cur.val) {
while (cur.next != null && cur.next.val == cur.val) cur = cur.next;
prev.next = cur.next;
} else prev = cur;
}
return dummy.next;
}
}
func deleteDuplicates(head *ListNode) *ListNode {
dummy := &ListNode{Next: head}
prev := dummy
for prev.Next != nil {
cur := prev.Next
if cur.Next != nil && cur.Next.Val == cur.Val {
for cur.Next != nil && cur.Next.Val == cur.Val {
cur = cur.Next
}
prev.Next = cur.Next // drop the whole run
} else {
prev = cur
}
}
return dummy.Next
}