0

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.

2
  • Are you expecting your code to remove all the elements at the start of the list with the given key value? If the key value at the start of the list is not the one you're searching for, it won't remove a thing. Are you planning to release the memory associated with the released nodes? Are you planning to release nodes with the value further down the list (say the list is [0, 0, 1, 2, 1, 0, 2], then should the code delete both those 1's? It certainly won't at the moment. You need to step through a couple of sample lists to see what you need to do. Then implement that code. Commented Oct 20, 2013 at 19:41
  • @JonathanLeffler well, I know. The main point is that I want to know why the pointer to pointer doesn't work in this function, and I ignore other stuff like remove nodes in [0,0,1,2,1,0,2]. Anyway, thank you for your comment. Commented Oct 20, 2013 at 19:46

1 Answer 1

2
   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.

Sign up to request clarification or add additional context in comments.

1 Comment

ooh, I see. It should be *head = prev. Thank you for your quick response! +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.