-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove duplicates from an unsorted linked list.java
118 lines (106 loc) · 2.4 KB
/
Remove duplicates from an unsorted linked list.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//{ Driver Code Starts
/* package whatever; // don't place package name! */
import java.util.*;
import java.io.*;
class Node
{
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class Remove_Duplicate_From_LL
{
Node head;
Node temp;
public void addToTheLast(Node node)
{
if (head == null)
{
head = node;
temp = node;
}
else{
temp.next = node;
temp = node;
}
}
void printList(PrintWriter out)
{
Node temp = head;
while (temp != null)
{
out.print(temp.data+" ");
temp = temp.next;
}
out.println();
}
/* Drier program to test above functions */
public static void main(String args[])throws IOException
{
/* Constructed Linked List is 1->2->3->4->5->6->
7->8->8->9->null */
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int t=Integer.parseInt(in.readLine().trim());
while(t>0)
{
int n = Integer.parseInt(in.readLine().trim());
Remove_Duplicate_From_LL llist = new Remove_Duplicate_From_LL();
String s[]=in.readLine().trim().split(" ");
int a1=Integer.parseInt(s[0]);
Node head= new Node(a1);
llist.addToTheLast(head);
for (int i = 1; i < n; i++)
{
int a = Integer.parseInt(s[i]);
llist.addToTheLast(new Node(a));
}
//llist.printList();
Solution g = new Solution();
llist.head = g.removeDuplicates(llist.head);
llist.printList(out);
t--;
}
out.close();
}
}
// } Driver Code Ends
/* The structure of linked list is the following
class Node
{
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
*/
class Solution
{
//Function to remove duplicates from unsorted linked list.
public Node removeDuplicates(Node head)
{
// Your code here
LinkedHashSet<Integer> hset=new LinkedHashSet<>();
Node temp=head;
while(temp!=null)
{
hset.add(temp.data);
temp=temp.next;
}
temp=head;
Node prev=null;
for(Integer i:hset)
{
temp.data=i;
prev=temp;
temp=temp.next;
}
prev.next=null;
return head;
}
}