-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRemoveDuplicates.java
58 lines (51 loc) · 1.68 KB
/
RemoveDuplicates.java
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
55
56
57
58
// Write a removeDuplicates() function which takes a list and deletes any duplicate nodes from the list.
// The list is not sorted.
// For example if the linked list is 12->11->12->21->41->43->21 then
// removeDuplicates() should convert the list to 12->11->21->41->43.
import java.util.HashSet;
class LinkedList{
static class Node{
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
static void removeDuplicates(Node head){
HashSet<Integer> s = new HashSet<>();
Node current = head;
Node prev = null;
while(current != null){
int currentValue = current.data;
if(s.contains(currentValue))
prev.next = current.next; //skip that duplicate item.
else{
s.add(currentValue);
prev = current;
}
current = current.next;
}
}
static void print(Node node){
while(node != null){
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String args[]){
Node start = new Node(12);
start.next = new Node(11);
start.next.next = new Node(12);
start.next.next.next = new Node(21);
start.next.next.next.next = new Node(41);
start.next.next.next.next.next = new Node(43);
start.next.next.next.next.next.next = new Node(11);
System.out.println("original list - ");
print(start);
System.out.println("After removal of duplicates - ");
removeDuplicates(start);
print(start);
}
}