-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveLinkedList.java
65 lines (58 loc) · 1.55 KB
/
RemoveLinkedList.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
import java.util.HashSet;
public class RemoveLinkedList {
Node root;
public static class Node {
int data;
Node next;
Node(int val) {
data = val;
next = null;
}
}
public void add(int value) {
Node newNode = new Node(value);
if (root == null) {
root = newNode;
} else {
Node current = root;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void printList() {
Node current = root;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void removeDuplicates(RemoveLinkedList list){
HashSet<Integer> elements = new HashSet<>();
Node curr = list.root;
Node prev = null;
while(curr!=null){
if(elements.contains(curr.data)){
prev.next=curr.next;
}else{
elements.add(curr.data);
prev=curr;
}
curr=curr.next;
}
}
public static void main(String[] args) {
RemoveLinkedList linkedList = new RemoveLinkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(1);
linkedList.add(2);
linkedList.add(7);
linkedList.printList();
removeDuplicates(linkedList);
linkedList.printList();
}
}