Skip to content

Commit 4d06c5f

Browse files
Add remove duplicate nodes from a sorted linked list algorithm (TheAlgorithms#2452)
1 parent 972f134 commit 4d06c5f

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package DataStructures.Lists;
2+
3+
import DataStructures.Lists.Node;
4+
5+
public class RemoveDuplicateNodes {
6+
7+
public Node deleteDuplicates(Node head) {
8+
// sentinel
9+
Node sentinel = new Node(0, head);
10+
11+
// predecessor = the last node
12+
// before the sublist of duplicates
13+
Node pred = sentinel;
14+
15+
while (head != null) {
16+
// if it's a beginning of duplicates sublist
17+
// skip all duplicates
18+
if (head.next != null && head.value == head.next.value) {
19+
// move till the end of duplicates sublist
20+
while (head.next != null && head.value == head.next.value) {
21+
head = head.next;
22+
}
23+
// skip all duplicates
24+
pred.next = head.next;
25+
// otherwise, move predecessor
26+
} else {
27+
pred = pred.next;
28+
}
29+
30+
// move forward
31+
head = head.next;
32+
}
33+
return sentinel.next;
34+
}
35+
36+
public void print(Node head) {
37+
Node temp = head;
38+
while (temp != null && temp.next != null) {
39+
System.out.print(temp.value + "->");
40+
temp = temp.next;
41+
}
42+
if (temp != null) {
43+
System.out.print(temp.value);
44+
}
45+
}
46+
47+
public static void main(String arg[]) {
48+
RemoveDuplicateNodes instance = new RemoveDuplicateNodes();
49+
Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
50+
head = instance.deleteDuplicates(head);
51+
instance.print(head);
52+
}
53+
}

0 commit comments

Comments
 (0)