Deleting first node in linked list has problems

前端 未结 3 1565
鱼传尺愫
鱼传尺愫 2021-01-25 10:05

I\'m implementing a linked list and it needs to have a function that when given a head of a linked list and a cstring, it finds and deletes a node whose value is the cstring.

3条回答
  •  感情败类
    2021-01-25 10:52

    You are changing the root inside the function, thus you need to pass a double pointer:

    bool findAndRemove(node** root, char phrase[21])
    {
        node* iterate = *root;
        if(root != NULL && *root != NULL)
        {
            node* previous = NULL;
            while(iterate->next != NULL)
            {
                if(strcmp(iterate->entry, phrase) == 0)//found
                {
                    if(previous == NULL)//node to delete is at head
                    {
                        node* tmp = iterate;
                        *root = iterate->next;
                        free(tmp);
                        return true;
                    }
                    previous->next = iterate->next;
                    free(iterate);
                    return true;
                }
                previous = iterate;
                iterate = iterate->next;
            }
            return false;
        }
    }
    

提交回复
热议问题