-
Notifications
You must be signed in to change notification settings - Fork 20
/
RemoveDuplicatesFromSortedList.java
46 lines (39 loc) · 1.13 KB
/
RemoveDuplicatesFromSortedList.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
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* <p>
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
* <p>
* Accepted.
*/
public class RemoveDuplicatesFromSortedList {
public ListNode deleteDuplicates(ListNode head) {
ListNode node = head;
while (node != null && node.next != null) {
if (node.val == node.next.val) {
ListNode tmp = node.next;
node.next = tmp.next;
tmp.next = null;
} else {
node = node.next;
}
}
return head;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ListNode) {
ListNode node = (ListNode) obj;
return this.next == null && node.next == null || this.val == node.val && (this.next != null) && this.next.equals(node.next);
}
return false;
}
}
}