Home > Software design >  In Remove Duplicates from Sorted List problem whilst preserving order, I don't know why there i
In Remove Duplicates from Sorted List problem whilst preserving order, I don't know why there i

Time:10-08

struct ListNode* deleteDuplicates(struct ListNode* head)
{
     struct ListNode *p,*q,*t;
    p=head;
    q=head->next;
    while(p!=NULL)
    {
        if(p->val==q->val)
        {
            p->next=q->next;
            t=q;
            q=q->next;
            free(t);
        }
        else
        {
            p=q;
            q=q->next;
        }
    }
    return head;
}

Error Message Shown as: Line 19: Char 21: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]

CodePudding user response:

The logic is "backwards", it tries to check if the local element is the same as the next element, instead of checking if it's the same as the previous.

Consider a list of one element, and it's obvious how it breaks when dereferencing head->next->val.

CodePudding user response:

If the pointer head or q is a null pointer then these statements

q=head->next;

if(p->val==q->val)

and

q=q->next;

invoke undefined behavior.

The function can be defined the following way

struct ListNode * deleteDuplicates( struct ListNode *head )
{
    for ( struct ListNode *p = head; p != NULL && p->next != NULL; )
    {
        if ( p->val == p->next->val )
        {
            struct ListNode *tmp = p->next;
            p->next = p->next->next;
            free( tmp );
        }
        else
        {
            p = p->next;
        }
    }

    return head;
}
  • Related