This repository was archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathRemoveDuplicatesWithValue.java
102 lines (65 loc) · 1.99 KB
/
RemoveDuplicatesWithValue.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*-- Remove all the appereances of the Node with values having duplicates --*/
import java.util.*;
public class RemoveDuplicatesWithValue {
/*-- Method for removing duplicates including the original occurance from a LinkedList --*/
static Node removeAllDuplicates(Node A) {
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
while(A!=null){
Integer i = map.get(A.data);
/*--- Getting all the node values ---*/
if(i==null)
map.put(A.data, 1);
else
map.put(A.data, i+1);
A = A.next;
}
LinkedList<Node> list = new LinkedList<>();
for(Integer n : map.keySet()){
if(map.get(n)==1){
list.add(new Node(n));
}
}
if(list.size()==0)
return null;
Node llist = list.get(0);
Node lllist = llist;
for(int i=1; i<list.size(); i++){
lllist.next = list.get(i);
lllist = lllist.next;
}
return llist;
}
/*-- Inputs from the main method --*/
public static void main(String[] args){
Node A = new Node(5);
A.addNodeToTail(10);
A.addNodeToTail(20);
A.addNodeToTail(30);
A.addNodeToTail(30);
A.addNodeToTail(40);
A.addNodeToTail(50);
Node C = removeAllDuplicates(A);
while(C!=null){
System.out.println(C.data);
C = C.next;
}
}
}
/*-- Node class Implementation --*/
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
public void addNodeToTail(int addData){
Node current = this;
while(current!=null){
if(current.next==null){
current.next = new Node(addData);
break;
}
current = current.next;
}
}
}