【剑指Offer】删除链表中重复的结点

题目

在一个排序的链表中,如何删除重复的结点?

实现

1
2
3
4
5
6
7
8
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}
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
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null)
return null;

ListNode current = pHead;
ListNode prev = null;

while (current != null && current.next != null) {
if (current.next.val > current.val) {
prev = current;
current = current.next;
}
else {
while (current.next != null && current.next.val == current.val)
current = current.next;

current = current.next;

if (prev != null)
prev.next = current;
else
pHead = current;
}
}

return pHead;
}