82. Remove Duplicates from Sorted List II

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

解法1:

用dummy node解决。slow表示下一个插入位置。fast表示当前的元素。fast和它下一个元素相比,如果相同则跳过。
最后再按照两种情况分别处理,一个是slow指向的下一个元素就是fast,也就是说fast原来指向的数值是unique的,那么slow和fast都向前移动。
如果slow下一个元素和fast不同,那么需要跳过slow和fast当中的元素。
C++

1

Java

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy, fast = head;
while (fast != null) {
while (fast.next != null && fast.val == fast.next.val) {
fast = fast.next;
}
if (slow.next != fast) {
slow.next = fast.next;
fast = slow.next;
} else {
slow = slow.next;
fast = fast.next;
}
}
return dummy.next;
}
}