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; 
        return NULL;
    while((p->next!=NULL && q!=NULL)){
          Node* r=q;
         if((p->data != q->data)&&( q!=NULL)){
    return head;


asked Jan 8, 2017 by anonymous
retagged Jan 8, 2017

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 first check if q is not null.. Just apply it...Gonna work..

answered Jan 8, 2017 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 will work..

Ok! Thanks! @sahil_coder