Home >>Cpp Programs >Remove Duplicates from linked list in c++
In this example, we will see a C++ program through which we can eliminate the duplicates from a given link list.
In this program, we will keep the temp pointer pointing to node while (temp -> next != NULL), we will check if the data of temp is equal to data of temp->next. If they are equal then we will point the temp-> next to temp -> next ->next.
Program:
#include <bits/stdc++.h>
using namespace std;
struct Node{// linked list Node
int data;
Node * next;
};
Node *newNode(int k){ //defining new node
Node *temp = (Node*)malloc(sizeof(Node));
temp->data = k;
temp->next = NULL;
return temp;
}
//Used to add new node at the end of the list
Node *addNode(Node* head, int k){
if(head == NULL){
head = newNode(k);
}
else{
Node * temp = head;
Node * node = newNode(k);
while(temp->next!= NULL){
temp = temp->next;
}
temp-> next = node;
}
return head;
}
// Used to create new linked list and return head
Node *createNewLL(){
int cont = 1;
int data;
Node* head = NULL;
while(cont){
cout<<"Enter the data of the Node"<<endl;
cin>>data;
head = addNode(head,data);
cout<<"Do you want to continue?(0/1)"<<endl;
cin>>cont;
}
return head;
}
//To print the Linked List
void *printLL(Node * head){
while(head!= NULL){
cout<<head->data<<"->";
head = head-> next;
}
cout<<"NULL"<<endl;
}
//Function
Node *removeDuplicate(Node* head){
//temp pointing to head
Node *temp = head;
while(temp->next != NULL && temp != NULL){
//Duplicate Found
if(temp->data == temp->next->data){
//DUplicate Removed
temp -> next = temp ->next ->next;
}
else{
//No Duplicate Present
temp = temp->next;
}
}
//Return Head
return head;
}
//Driver Main
int main(){
Node * head = createNewLL();
cout<<"The linked list is"<<endl;
printLL(head);
head = removeDuplicate(head);
cout<<"The new Linked List is" <<endl;
printLL(head);
return 0;
}