Geek
Geek

Reputation: 59

Removing duplicates from linked lists

#include<iostream>
using namespace std;

struct Node{
int data=0;
Node* next=NULL;
};

void removeDuplicates(Node* head){  
Node *ptr,*ptr2,*temp;
ptr=head;


while(ptr->next!=NULL && ptr!=NULL){
    ptr2=ptr;
    while(ptr2->next!=NULL){
        if(ptr2->next->data==ptr->data){
            temp=ptr2->next;
            ptr2->next=temp->next; 
            
            temp->next=NULL;
            delete(temp);
            
        }
        else ptr2=ptr2->next;   
    }
    ptr=ptr->next;
} 
}
void display(Node *head){
Node* ptr=head;
while(ptr!=NULL){
    cout<<ptr->data<<" ";
    ptr=ptr->next;
}
cout<<endl;
}

int main(){
int n;
cin>>n;
Node* head=NULL;
Node *tail=NULL;
for(int i=0;i<n;i++){
    Node *newNode=new Node();
    
    cin>>newNode->data;
    
    if(head==NULL){
        head=newNode;
        tail=newNode;
    } 
    else{
        tail->next=newNode;
        tail=newNode;   
    }
}
display(head);
removeDuplicates(head);
display(head);

}

The above code is to remove duplicate elements in linked list . The above code is not showing any result when the last element of the list is a repeated element .eg (2 1 1 2 1) ,(1 1 1 1) The code is working fine for (1 2 1 3) (1 2 1 2 3) Any help will be appreciated.

Upvotes: 0

Views: 62

Answers (1)

Geek
Geek

Reputation: 59

the error here was was in the 1st while loop in the removeDuplicate(head) function

while(ptr->next!=NULL && ptr!=NULL)

It is necessary to put ptr!=NULL condition before the ptr->next!=NULL otherwise segmentation fault Please learn from my experience :)

Upvotes: 2

Related Questions