-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveDup_sortedlist.java
More file actions
57 lines (53 loc) · 1.47 KB
/
removeDup_sortedlist.java
File metadata and controls
57 lines (53 loc) · 1.47 KB
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
/*
Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return null;
ListNode result=new ListNode(head.val);
ListNode tracking=result;
ListNode curr=head;
curr=curr.next;
while(curr!= null){
if(tracking.val == curr.val){
// pass this node
}else{
// add this node
tracking.next = new ListNode(curr.val);
tracking = tracking.next;
}
curr = curr.next;
}
return result;
}
}
//time limit error
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return null;
ListNode nodup=new ListNode(0); nodup.next=head;
ListNode temp=head;
while(temp.next!=null){
ListNode tempNext=temp.next;
if(tempNext.next==null) return nodup.next;
if(tempNext.val==temp.val) tempNext=tempNext.next;
else temp.next=temp;
}
return nodup.next;
}
}