In this C++ tutorial, we will learn how to remove all the duplicate entries from a sorted linked list. Here is the code for the algorithm in C++ :
Output: 9 8 8 8 7 6 6 5 5 5 5 5 5 5 4 3 3 2 1
After removing the duplicates -
9 8 7 6 5 4 3 2 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
class Node { | |
public: | |
int data; | |
Node* next; | |
}; | |
void push(Node **head_ref, int new_data) { | |
Node *new_node = new Node(); | |
new_node->data = new_data; | |
new_node->next = *head_ref; | |
*head_ref = new_node; | |
} | |
void printList(Node* node) { | |
while(node != NULL) { | |
cout<<node->data<<endl; | |
node = node->next; | |
} | |
} | |
void removeDuplicate(Node* head) { | |
Node* after; | |
if(head == NULL) | |
return; | |
while(head->next != NULL) { | |
if(head->data == head->next->data){ | |
after = head->next->next; | |
delete head->next; | |
head->next = after; | |
continue; | |
} | |
head = head->next; | |
} | |
} | |
int main() { | |
Node *head = NULL; | |
push(&head, 1); | |
push(&head, 2); | |
push(&head, 3); | |
push(&head, 3); | |
push(&head, 4); | |
push(&head, 5); | |
push(&head, 5); | |
push(&head, 5); | |
push(&head, 5); | |
push(&head, 5); | |
push(&head, 5); | |
push(&head, 5); | |
push(&head, 6); | |
push(&head, 6); | |
push(&head, 7); | |
push(&head, 8); | |
push(&head, 8); | |
push(&head, 9); | |
printList(head); | |
cout<<endl; | |
removeDuplicate(head); | |
printList(head); | |
return 0; | |
} |
Output: 9 8 8 8 7 6 6 5 5 5 5 5 5 5 4 3 3 2 1
After removing the duplicates -
9 8 7 6 5 4 3 2 1
No comments:
Post a Comment