Skip to content

Commit 808b657

Browse files
committed
Remove Duplicates in Sorted Linked List
1 parent b08611c commit 808b657

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
if(current->next != NULL && current->data == current->next->data){
15+
Node * nextNode = current->next->next;
16+
Node * nodetodelete = current->next;
17+
delete nodetodelete;
18+
current->next = nextNode;
19+
}
20+
else{
21+
current = current->next;
22+
}
23+
}
24+
return head;
25+
}
26+
void printList(Node * head){
27+
Node * temp = head;
28+
while(temp != NULL){
29+
cout << temp->data << " ";
30+
temp = temp->next;
31+
}
32+
cout << endl;
33+
}
34+
int main(){
35+
Node * head = new Node(1);
36+
head->next = new Node(2);
37+
head->next->next = new Node(2);
38+
head->next->next->next = new Node(3);
39+
head->next->next->next->next = new Node(3);
40+
head->next->next->next->next->next = new Node(4);
41+
cout << "Original Linked List: ";
42+
printList(head);
43+
head = removeDuplicates(head);
44+
cout << "Linked List After Removing Duplicates: ";
45+
printList(head);
46+
return 0;
47+
}

0 commit comments

Comments
 (0)