Skip to content

Commit b7bd3cf

Browse files
committed
removeDuplicatesFromSortedList.II
1 parent 3abe7f7 commit b7bd3cf

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) {
7+
* val = x;
8+
* next = null;
9+
* }
10+
* }
11+
*/
12+
public class Solution {
13+
public ListNode deleteDuplicates(ListNode head) {
14+
if (head == null || head.next == null) { return head; }
15+
ListNode fakeHead = new ListNode(0);
16+
fakeHead.next = head;
17+
ListNode b = fakeHead;
18+
ListNode f = head;
19+
boolean isDuplicated = false;
20+
int val = 0;
21+
while (f != null) {
22+
if (isDuplicated) {
23+
if (f.val != val) {
24+
isDuplicated = false;
25+
b.next = f;
26+
}
27+
}
28+
if (!isDuplicated && f.next != null) {
29+
if (f.next.val != f.val) {
30+
b = f;
31+
} else {
32+
isDuplicated = true;
33+
val = f.val;
34+
}
35+
}
36+
f = f.next;
37+
}
38+
if (isDuplicated) {
39+
b.next = null;
40+
}
41+
return fakeHead.next;
42+
}
43+
}

0 commit comments

Comments
 (0)