-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRemoveDuplicate.java
78 lines (58 loc) · 1.26 KB
/
RemoveDuplicate.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
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
void remove_duplicates()
{
Node ptr1 = null,
ptr2 = null,
dup = null;
ptr1 = head;
while (ptr1 != null && ptr1.next != null) {
ptr2 = ptr1;
while (ptr2.next != null) {
if (ptr1.data == ptr2.next.data) {
ptr2.next = ptr2.next.next;
System.gc();
}
else {
ptr2 = ptr2.next;
}
}
ptr1 = ptr1.next;
}
}
void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args){
LinkedList list = new LinkedList();
list.head = new Node(12);
list.head.next = new Node(11);
list.head.next.next = new Node(12);
list.head.next.next.next = new Node(21);0
list.head.next.next.next.next = new Node(41);
list.head.next.next.next.next.next = new Node(43);
list.head.next.next.next.next.next.next
= new Node(21);
System.out.println(
"Linked List before removing duplicates : ");
list.printList(head);
list.remove_duplicates();
System.out.println("\n");
System.out.println(
"Linked List after removing duplicates : ");
list.printList(head);
}
}