# 82. Remove Duplicates from Sorted List II

• Time: $O(n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode dummy(0, head); ListNode* prev = &dummy; while (head) { while (head->next && head->val == head->next->val) head = head->next; if (prev->next == head) prev = prev->next; else prev->next = head->next; head = head->next; } return dummy.next; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(0, head); ListNode prev = dummy; while (head != null) { while (head.next != null && head.val == head.next.val) head = head.next; if (prev.next == head) prev = prev.next; else prev.next = head.next; head = head.next; } return dummy.next; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: dummy = ListNode(0, head) prev = dummy while head: while head.next and head.val == head.next.val: head = head.next if prev.next == head: prev = prev.next else: prev.next = head.next head = head.next return dummy.next