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.