0
#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.

1
  • 3
    For things like lists my suggestion is that you take the simple list you have and draw it on paper using a pencil. Use boxes for the nodes and arrows for the pointers (including the links). Then try to perform the operations by erasing and redrawing the arrows. Detail all the steps you make. Once you think you got it to work on paper you translate that algorithm into code that you write and test. If it doesn't work, use a debugger to step through the code and make sure it follows the step you written down on the paper (and draw the operations your program does as well). Commented Aug 28, 2021 at 10:43

1 Answer 1

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.