From 25817272cae4b4722807532efbab2daa95b92479 Mon Sep 17 00:00:00 2001 From: SUBHAM KUMAR PANDEY Date: Fri, 10 Sep 2021 18:19:02 +0530 Subject: [PATCH] chore(CPlusPlus): add remove-duplicates-in-sorted-linked-list (#453) --- ...emove-duplicates-in-sorted-linked-list.cpp | 68 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 69 insertions(+) create mode 100644 algorithms/CPlusPlus/Linked-Lists/remove-duplicates-in-sorted-linked-list.cpp diff --git a/algorithms/CPlusPlus/Linked-Lists/remove-duplicates-in-sorted-linked-list.cpp b/algorithms/CPlusPlus/Linked-Lists/remove-duplicates-in-sorted-linked-list.cpp new file mode 100644 index 00000000..fc06fb82 --- /dev/null +++ b/algorithms/CPlusPlus/Linked-Lists/remove-duplicates-in-sorted-linked-list.cpp @@ -0,0 +1,68 @@ +//Program to Remove Duplicates in Sorted Singly linkedlist + + +// Algorithm: + +//Traverse the list from the head (or start) node. +//While traversing, compare each node with its next node. +//If the data of the next node is the same as the current node then delete the next node. +//Before we delete a node, we need to store the next pointer of the node + + +//Implementation: +#include +using namespace std; + +/* a node of the singly linked list */ +struct Node{ + int data; + Node* next; + Node(int x){ + data=x; + next=NULL; + } +}; + +/* Function to print nodes in a given linked list */ +void printlist(Node *head){ + Node *curr=head; + while(curr!=NULL){ + cout<data<<" "; + curr=curr->next; + }cout<next!=NULL){ + if(curr->data==curr->next->data){ + Node *temp=curr->next; + curr->next=curr->next->next; + delete temp; + } + else{ + curr=curr->next; + } + } +} + +int main() +{ + Node *head=new Node(10); + head->next=new Node(11); + head->next->next=new Node(11); + head->next->next->next=new Node(13); + head->next->next->next->next=new Node(13); + head->next->next->next->next->next=new Node(15); + printlist(head); + removeduplicates(head); + printlist(head); + return 0; +} +/* +Input: 10 11 11 13 13 15 +Output: 10 11 13 15 +Time Complexity: O(n) where n is the number of nodes in the given linked list. +*/ diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 786f6400..2095213f 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -46,6 +46,7 @@ 9. [Detecting cycle in a singly linked list](Linked-Lists/Cycle-Detection.cpp) 10. [Find Merge Point of two singly linked list](Linked-Lists/Find-Merge-Point.cpp) 11. [Segregate Even Odd Nodes of linked list](Linked-Lists/segregate-even-odd-nodes-of-linked-list.cpp) +12. [Remove Duplicate in Sorted linked list](Linked-Lists/remove-duplicates-in-sorted-linked-list.cpp) ## Searching