mitchelllc
mitchelllc

Reputation: 1657

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.

Upvotes: 0

Views: 2135

Answers (1)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143071

   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.

Upvotes: 2

Related Questions