Skip to content

Commit 31fe752

Browse files
Removing Duplicate in unsorted list using Hashing
1 parent 5d602dd commit 31fe752

File tree

2 files changed

+59
-10
lines changed

2 files changed

+59
-10
lines changed

DataStructures/LinkedList/com/java4u/ds/linkedlist/removeDuplicates/RemoveDuplicates.java

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.java4u.ds.linkedlist.removeDuplicates;
2+
3+
import java.util.HashSet;
4+
5+
import com.java4u.ds.linkedlist.Node;
6+
7+
public class RemoveDuplicatesUsingHashing {
8+
9+
public Node removeDuplicateInList(Node head) {
10+
if (head == null) {
11+
return head;
12+
}
13+
HashSet<Integer> set = new HashSet<>();
14+
Node current = head;
15+
Node prev = null;
16+
while (current != null) {
17+
int curval = current.getData();
18+
if (set.contains(curval)) {
19+
prev.setNext(current.getNext());
20+
} else {
21+
set.add(curval);
22+
prev = current;
23+
}
24+
current = current.getNext();
25+
}
26+
return head;
27+
}
28+
29+
static void print(Node head) {
30+
while (head != null) {
31+
System.out.print(head.data + " ");
32+
head = head.next;
33+
}
34+
System.out.println();
35+
}
36+
37+
public static void main(String[] args) {
38+
Node head = new Node(1);
39+
Node n1 = new Node(2);
40+
Node n2 = new Node(3);
41+
Node n3 = new Node(4);
42+
Node n4 = new Node(5);
43+
Node n5 = new Node(2);
44+
Node n6 = new Node(6);
45+
46+
head.setNext(n1);
47+
n1.setNext(n2);
48+
n2.setNext(n3);
49+
n3.setNext(n4);
50+
n4.setNext(n5);
51+
n5.setNext(n6);
52+
53+
print(head);
54+
Node node = new RemoveDuplicatesUsingHashing().removeDuplicateInList(head);
55+
print(node);
56+
57+
}
58+
59+
}

0 commit comments

Comments
 (0)