Skip to content

Commit f4ad7cd

Browse files
committed
Remove Duplicates from a Unsorted Linked List.
1 parent 808b657 commit f4ad7cd

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include<iostream>
2+
using namespace std;
3+
struct Node{
4+
int data;
5+
Node * next;
6+
Node(int val): data(val), next(nullptr) {}
7+
};
8+
Node * removeDuplicates(Node * head){
9+
if(head == NULL){
10+
return NULL;
11+
}
12+
Node * current = head;
13+
while(current != NULL){
14+
Node * runner = current; // Use a runner to iterate from current->next
15+
while(runner->next != NULL){ // Iterate until the second to last node
16+
if(runner->next->data == current->data){ // Check the next node's data
17+
Node * nodetodelete = runner->next;
18+
runner->next = runner->next->next;
19+
delete nodetodelete;
20+
}
21+
else{
22+
runner = runner->next;
23+
}
24+
}
25+
current = current->next;
26+
}
27+
return head;
28+
}
29+
void printList(Node * head){
30+
Node * curr = head;
31+
while(curr != NULL){
32+
cout << curr->data << " ";
33+
curr = curr->next;
34+
}
35+
cout << endl;
36+
}
37+
int main(){
38+
Node * head = new Node(5);
39+
head->next = new Node(3);
40+
head->next->next = new Node(4);
41+
head->next->next->next = new Node(3);
42+
head->next->next->next->next = new Node(5);
43+
cout << "Original Linked List: ";
44+
printList(head);
45+
head = removeDuplicates(head);
46+
cout << "Linked List After Removing Duplicates: ";
47+
printList(head);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)