LeetCode: Remove Duplicates from Sorted List

LeetCode: Remove Duplicates from Sorted List

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

/**
* Description:
*
* @author hzhou
*/
public class RemoveDuplicatesFromSortedList {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cursor, pre;
pre = head;
cursor = head.next;
while (cursor != null) {
while (cursor != null && cursor.val == pre.val) {
cursor = cursor.next;
}
if (cursor == null) {
pre.next = null;
} else {
pre.next = cursor;
pre = pre.next;
cursor = cursor.next;
}
}
return head;
}
}