简体   繁体   中英

remove a node in linked list using pointer to pointer in C

I want to remove nodes whose values are N in a linked list. Below is the definition of the linked list and remove function I wrote.

typedef struct LinkedList {
    int val;
    struct LinkedList *next;
} LinkedList;

void removeNode(int val, LinkedList **head) {
   LinkedList *prev = *head;

   while (prev && prev->val == val)
       prev = prev->next;
   head = &prev;
   if (*head == NULL)
       return;

   // other stuff
}

In order to test if the pointer to pointer works or not in this function, I wrote the following function.

int main() {
    LinkedList root;
    root.val = 1;
    root.next = NULL;
    LinkedList *head = &root;

    removeNode(1, &head);

    if (head == NULL)
        printf("%s\d", "Empty");
    else
        printf("%d\n", head->val);

    return 0;
}

I think the output will be "Empty" as removeNode function will modify the head pointer to NULL . However, the output is 1 .

My question is why the pointer to pointer doesn't change head in removeNode function. All suggestions are welcome.

Update:

Thanks for Michael's reply. The correct way to modify head is *head = prev , not head = &prev .

   head = &prev;

You modify head , not *head . And I doubt you want to assign the address of prev to it. Still haven't checked the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM