-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeleteDuplicatesFromSortedList2.java
63 lines (62 loc) · 1.83 KB
/
DeleteDuplicatesFromSortedList2.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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class DeleteDuplicatesFromSortedList2 {
/*
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List II.
Memory Usage: 38.5 MB, less than 35.97% of Java online submissions for Remove Duplicates from Sorted List II.
*/
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return null;
if(head!=null && head.next==null) return head;
ListNode slow=head;
ListNode fast=head.next;
ListNode newhead=null,tail=null;
boolean isMatchedbefore=false;
while(fast!=null)
{
//System.out.println("Slow Pointer : "+slow.val);
if(slow.val!=fast.val)
{
if(!isMatchedbefore)
{
if(tail==null)
{
tail=new ListNode(slow.val);
newhead=tail;
}
else
{
tail.next=new ListNode(slow.val);
tail=tail.next;
}
}
isMatchedbefore=false;
}
else
{
isMatchedbefore=true;
}
slow=slow.next;fast=fast.next;
}
if(!isMatchedbefore) {
if(tail==null)
{
newhead=new ListNode(slow.val);
}
else
{
tail.next=new ListNode(slow.val);
tail=tail.next;
}
}
return newhead;
}
}