GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Delete Duplicate Nodes in a Linked List

I have written a simple code snippet to delete duplicate nodes in a linked list.But I am getting segmentation fault.What could be the reason?

Node* RemoveDuplicates(Node *head)
{
    Node *p=head,*q=head; 
  
    if(head==NULL){
        return NULL;
    }
    else{
        q=q->next;
    while((p->next!=NULL && q!=NULL)){
       if(p->data==q->data){
        p->next=q->next;
          Node* r=q;
           q=p->next;
        free(r);
       }
         if((p->data != q->data)&&( q!=NULL)){
            p=p->next;
            q=q->next;
        }      
    }   
    }
    return head;
}

 

asked Jan 8 by anonymous
retagged Jan 8

1 Answer

Just modify ur condition from (p->data != q->data)&&( q!=NULL) to

( q!=NULL) && (p->data != q->data)..
 u r first checking q->data but q can be NULL at that time...so first check if q is not null.. Just apply it...Gonna work..

answered Jan 8 by sahil_coder

@sahil_coder Thank you!! but i have put && if q is null entire statement will be zero

What is happening there exactly?

See, first u compare the data of p with data of q...and then u r checking if q is not null... But what if q is already null and first u checked data of q...mnz data of a null pointer...which is not in the memory...thats the reason for seg. Fault... So if u will chk that if q is not null then process further...it will work..

Ok! Thanks! @sahil_coder

...