Skip to content

Commit f18575e

Browse files
committed
Added a program to remove duplicates from an unsorted singlely liked list.
1 parent 90396a3 commit f18575e

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
class node{
2+
3+
constructor(data){
4+
5+
this.data=data;
6+
this.next=null;
7+
8+
}
9+
}
10+
11+
12+
class LinkedList{
13+
14+
constructor(){
15+
this.head=null;
16+
}
17+
18+
//Function to insert a node in the singlely linkedlist.
19+
insert=(data)=>{
20+
21+
var newnode=new node(data);
22+
if(head===null){
23+
this.head=newnode;
24+
}
25+
26+
else{
27+
28+
var temp=this.head;
29+
while(temp.next!==null){
30+
temp=temp.next;
31+
}
32+
33+
temp=newnode;
34+
}
35+
}
36+
37+
//Function to print the singlely linkedlist.
38+
printList=()=>{
39+
var temp=this.head;
40+
var list;
41+
while(temp!==null){
42+
list+=temp.data+"->";
43+
temp=temp.next;
44+
}
45+
list+="null";
46+
console.log(list);
47+
}
48+
49+
50+
51+
//Function to remove dupliicate nodes from the singlely linkedlist.
52+
removeDuplicates=()=>{
53+
54+
var temp1,temp2,duplicate;
55+
56+
temp1=this.head;
57+
temp2=temp1;
58+
while(temp1!==null || temp.next!==null){
59+
60+
while(temp2.next!==null){
61+
if(temp1.data===temp2.next.data){
62+
duplicate=temp2.next;
63+
temp2.next=temp2.next.next;
64+
delete(duplicate);
65+
}
66+
else{
67+
temp2=temp2.next;
68+
}
69+
}
70+
temp1=temp1.next;
71+
}
72+
73+
}
74+
75+
}
76+
77+
//main function.
78+
/*
79+
Linkedlist list;
80+
list.insert(0);
81+
list.insert(1);
82+
list.insert(2);
83+
list.insert(3);
84+
list.insert(1);
85+
list.insert(4);
86+
list.insert(4);
87+
console.log("Original List with DUplicates:");
88+
list.printList();
89+
list.removeDuplicates();
90+
console.log("List free of duplicates:");
91+
list.printList();
92+
*/
93+

0 commit comments

Comments
 (0)