-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveDuplicatesFromSortedListII.java
91 lines (82 loc) · 2.71 KB
/
RemoveDuplicatesFromSortedListII.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package leetcode;
import utils.ListNode;
import utils.Lists;
/**
* RemoveDuplicatesFromSortedListII
* https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
* 82. 删除排序链表中的重复元素 II
* https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/solution/zhi-zhen-cao-zuo-shan-chu-by-oshdyr-a3gg/
*
* @since 2021-03-25
*/
public class RemoveDuplicatesFromSortedListII {
public static void main(String[] args) {
RemoveDuplicatesFromSortedListII sol = new RemoveDuplicatesFromSortedListII();
ListNode l1 = Lists.fromInts(new int[]{1, 2, 3, 3, 4, 4, 5}, -1);
l1 = sol.deleteDuplicates(l1);
while (l1 != null) {
System.out.print(l1.val + ", ");
l1 = l1.next;
}
System.out.println();
ListNode l2 = Lists.fromInts(new int[]{1, 1, 1, 2, 3}, -1);
l2 = sol.deleteDuplicates(l2);
while (l2 != null) {
System.out.print(l2.val + ", ");
l2 = l2.next;
}
System.out.println();
ListNode l3 = Lists.fromInts(new int[]{1, 1}, -1);
l3 = sol.deleteDuplicates(l3);
while (l3 != null) {
System.out.print(l3.val + ", ");
l3 = l3.next;
}
System.out.println();
}
public ListNode deleteDuplicates(ListNode head) {
ListNode lastLast = null;
ListNode last = null;
boolean duplicatedLast = false;
ListNode newHead = head;
ListNode curr = newHead;
while (curr != null) {
if (last != null) {
if (last.val == curr.val) {
// remove curr
last.next = curr.next;
curr = last;
last = lastLast;
duplicatedLast = true;
} else {
if (duplicatedLast) {
// remove duplicated last
if (lastLast == null) {
newHead = curr;
last = null;
} else {
lastLast.next = curr;
last = lastLast;
}
duplicatedLast = false;
}
}
}
lastLast = last;
last = curr;
curr = curr.next;
}
if (duplicatedLast) {
// remove duplicated last
if (lastLast == null) {
newHead = null;
last = null;
} else {
lastLast.next = null;
last = lastLast;
}
duplicatedLast = false;
}
return newHead;
}
}