Delete element of linked list by a certain criterion

后端 未结 1 709
抹茶落季
抹茶落季 2020-12-12 06:23

I\'ve written this function:

List* delPaintingCode(List* head, char *code)
{
    List *p,*q;

    for(p=head;p!=NULL;q=p,p=p->next)
    {
        if(!strc         


        
相关标签:
1条回答
  • 2020-12-12 07:18

    The logical problem that leads to a crash is in the if (p==head) branch of your code: when you delete the initial element, you free the head without updating p. This leads to dereferencing a freed pointer on the very next iteration.

    You can fix the problem by introducing a fake node with head in its next, and returning the next, like this:

    List fake;
    fake.next = head;
    // This loop always looks ahead by one element, i.e. at p->next.
    for(List *p = &fake ; p->next != NULL ; p = p->next) {
        if(strcmp(code, p->next->code)) {
            continue;
        }
        List *q = p->next;
        p->next = q->next;
        free(q);
    }
    return fake.next;
    

    This approach works for the initial element, too, because we added a fake head to our list, so the first time around p->next is the same as head. This lets us unify treatment of head element and all other elements.

    0 讨论(0)
提交回复
热议问题