Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Return the linked list sorted as well.
Note: Unlike Remove Duplicates I, we remove ALL occurrences of duplicates, not just keep one.
Use a dummy node and track the previous non-duplicate node.
Input: 1→2→3→3→4→4→5
Step 1: 1 is unique, keep it
prev→1, check 2
Step 2: 2 is unique, keep it
prev→2, check 3
Step 3: 3 appears twice, remove both
Skip 3→3, prev still at 2
Step 4: 4 appears twice, remove both
Skip 4→4, prev still at 2
Step 5: 5 is unique, keep it
prev→5
Result: 1→2→5
1/**
2 * Remove Duplicates from Sorted List II
3 * Time: O(n), Space: O(1)
4 */
5
6class ListNode {
7 int val;
8 ListNode next;
9 ListNode() {}
10 ListNode(int val) { this.val = val; }
11 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
12}
13
14class Solution {
15 public ListNode deleteDuplicates(ListNode head) {
16 ListNode dummy = new ListNode(0);
17 dummy.next = head;
18 ListNode prev = dummy;
19
20 while (head != null) {
21 if (head.next != null && head.val == head.next.val) {
22 while (head.next != null && head.val == head.next.val) {
23 head = head.next;
24 }
25 prev.next = head.next;
26 } else {
27 prev = prev.next;
28 }
29
30 head = head.next;
31 }
32
33 return dummy.next;
34 }
35}
36