-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeleteDuplicates.java
More file actions
49 lines (40 loc) · 1.01 KB
/
Copy pathdeleteDuplicates.java
File metadata and controls
49 lines (40 loc) · 1.01 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
/*
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.
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class deleteDuplicates{
// Idea 0: Iteration
public ListNode deleteDuplicates0(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = head; // p as the moving pointer, keep "head" as the actual list head
while(p.next != null) {
if (p.val == p.next.val) {
p.next = p.next.next;
} else {
p = p.next;
}
}
return head;
}
// Idea 1: Recursion
public ListNode deleteDuplicates1(ListNode head) {
if (head == null || head.next == null) {
return head;
}
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
// head.next as the second node after original head, represents the list after the head
head.next = deleteDuplicates1(head.next);
return head;
}
}