-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRemoveDuplicatesfromSortedList.java
More file actions
54 lines (50 loc) · 1.32 KB
/
RemoveDuplicatesfromSortedList.java
File metadata and controls
54 lines (50 loc) · 1.32 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
package leetcode;
/**
* @author eko
* @date 2018/10/27 2:23 PM
*
* Given a sorted linked list, delete all duplicates such that each element appear only once.
*
* Example 1:
*
* Input: 1->1->2
* Output: 1->2
* Example 2:
*
* Input: 1->1->2->3->3
* Output: 1->2->3
*/
public class RemoveDuplicatesfromSortedList {
public static void main(String[] args) {
RemoveDuplicatesfromSortedList solution = new RemoveDuplicatesfromSortedList();
ListNode node = solution.new ListNode(1);
node.next = solution.new ListNode(1);
node.next.next = solution.new ListNode(2);
ListNode res = solution.deleteDuplicates(node);
while (res != null) {
System.out.println(res.val);
res = res.next;
}
}
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return head;
ListNode currentNode = head;
ListNode index = head.next;
while (index != null) {
if (currentNode.val != index.val) {
currentNode.next = index;
currentNode = index;
}
index = index.next;
}
currentNode.next = null;
return head;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}