-
Notifications
You must be signed in to change notification settings - Fork 692
/
RemoveDuplicates.java
72 lines (56 loc) · 1.96 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package linkedlist;
import java.util.HashSet;
public class RemoveDuplicates {
/*
* Use hashset!!
* Runtime Complexity:
* Linear, O(n) - where 'n' is length of the linked list.
*
* Memory Complexity:
* Linear, O(n) - to store nodes in hashset.
* */
public static class LinkedList {
private Node head;
public Node removeDuplicates(Node head) {
Node currentNode = head;
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(currentNode.data);
while (currentNode.next != null) {
if(hashSet.contains(currentNode.next.data)) {
currentNode.next = currentNode.next.next;
} else {
hashSet.add(currentNode.next.data);
currentNode = currentNode.next;
}
}
return head;
}
public void print(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
}
public static void main(String [] args) {
LinkedList linkedList = new LinkedList();
linkedList.head = new LinkedList.Node(1);
linkedList.head.next = new LinkedList.Node(1);
linkedList.head.next.next = new LinkedList.Node(3);
linkedList.head.next.next.next = new LinkedList.Node(2);
linkedList.head.next.next.next.next = new LinkedList.Node(3);
linkedList.head.next.next.next.next.next = new LinkedList.Node(1);
linkedList.print(linkedList.head);
linkedList.head = linkedList.removeDuplicates(linkedList.head);
System.out.println("");
linkedList.print(linkedList.head);
}
}