-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveDuplicatesFromSortedListII.java
72 lines (65 loc) · 1.29 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
package ProjectFiles;
public class RemoveDuplicatesFromSortedListII {
public static void main(String[] args) {
}
private static ListNode deleteDuplicates(ListNode head) {
ListNode o = head;
if(head == null)
return head;
if(head.next == null)
return head;
ListNode temp = head;
ListNode prev = null ;
while(temp.next != null){
if(temp.next.val == temp.val){
while(temp.next != null && temp.next.val == temp.val){
temp.next = temp.next.next;
}
if(temp.next != null){
if(prev == null){
head = temp.next;
}else{
prev.next = temp.next;
}
temp = temp.next;
}
else{
if(prev == null){
return null;
}
prev.next = null;
}
}
else{
prev = temp;
temp = temp.next;
}
}
if(temp.val == o.val){
return null;
}
return head;
}
private static ListNode deleteDuplicates1(ListNode head) {
if(head == null)
return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev = dummy;
ListNode t = head;
while(t!= null && t.next != null){
if(t.next.val == t.val){
while(t.next != null && t.next.val == t.val){
t.next = t.next.next;
}
prev.next = t.next;
t = t.next;
}
else{
prev = t;
t = t.next;
}
}
return dummy.next;
}
}