leetcode(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.

Example 1:

1
2
Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

1
2
Input: 1->1->1->2->3
Output: 2->3

解法

没啥好解释的,就设置三个指针值,一个指向前一个节点,一个指向当前节点,一个指向下一个节点,注意删除整个头部对head的影响。

具体代码如下:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
class  {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode pre = head;
ListNode now = head;
ListNode next = head.next;
while (next != null) {
if (now.val != next.val) {
pre = now;
now = next;
next = now.next;
} else {
while (next != null) {
if (now.val == next.val) {
now = next;
next = now.next;
} else {
break;
}
}
if (next != null) {
if (head.val == now.val) {
head = next;
pre = head;
now = head;
next = head.next;
} else {
pre.next = next;
now = pre.next;
next = now.next;
}

} else {
if (head.val == now.val) {
head = null;
} else {
pre.next = next;
}

}
}
}
return head;
}
}