forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicateNodes.java
More file actions
53 lines (45 loc) · 1.55 KB
/
RemoveDuplicateNodes.java
File metadata and controls
53 lines (45 loc) · 1.55 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
package DataStructures.Lists;
import DataStructures.Lists.Node;
public class RemoveDuplicateNodes {
public Node deleteDuplicates(Node head) {
// sentinel
Node sentinel = new Node(0, head);
// predecessor = the last node
// before the sublist of duplicates
Node pred = sentinel;
while (head != null) {
// if it's a beginning of duplicates sublist
// skip all duplicates
if (head.next != null && head.value == head.next.value) {
// move till the end of duplicates sublist
while (head.next != null && head.value == head.next.value) {
head = head.next;
}
// skip all duplicates
pred.next = head.next;
// otherwise, move predecessor
} else {
pred = pred.next;
}
// move forward
head = head.next;
}
return sentinel.next;
}
public void print(Node head) {
Node temp = head;
while (temp != null && temp.next != null) {
System.out.print(temp.value + "->");
temp = temp.next;
}
if (temp != null) {
System.out.print(temp.value);
}
}
public static void main(String arg[]) {
RemoveDuplicateNodes instance = new RemoveDuplicateNodes();
Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
head = instance.deleteDuplicates(head);
instance.print(head);
}
}