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 18
Expand file tree
/
Copy pathDeleteDuplicateNodes.java
More file actions
73 lines (44 loc) · 1.35 KB
/
DeleteDuplicateNodes.java
File metadata and controls
73 lines (44 loc) · 1.35 KB
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
/*-- Removing duplicates from Linked List --*/
import java.util.*;
public class DeleteDuplicateNodes {
/*-- Removing duplicates from Linked List method --*/
public static Node removeDuplicatesFromLinkedList(Node head) {
if(head==null)
return null;
Node n = head;
LinkedHashSet<Integer> lhs = new LinkedHashSet<>();
while(n.next!=null){
lhs.add(n.data);
n = n.next;
}
lhs.add(n.data);
Iterator<Integer> it = lhs.iterator();
Node newHead = new Node(it.next());
Node listNodes = newHead;
while(it.hasNext()){
listNodes.next = new Node(it.next());
listNodes = listNodes.next;
}
return newHead;
}
/*-- Inputs from the main method --*/
public static void main(String[] args){
Node A = new Node(10);
A.next = new Node(10);
A.next.next = new Node(20);
A.next.next.next = new Node(20);
Node C = removeDuplicatesFromLinkedList(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;
}
}