Search code examples
cpointerslinked-listreturn

How to pop from linked list?


I've implemented a Linked-List with a Pop function in C:

Node * pop (Node * head) {
    Node * temp = head;

    printf("Temp is: %s\n", temp->val);

    if (head->next != NULL) {
        *head = *head->next;
    }

    printf("Temp is: %s\n", temp->val);
    return temp;
}

And the output when I pop would be something like:

Temp is: node1 value
Temp is: node2 value

That is to say that temp is becoming temp->next when I assign *head = *head->next.

So how can I get the value of the current head and return it while also moving the head of the Linked-list to head->next?

Doing head = head->next does NOT remove the reference to the first node. (i.e. When I print the list, the first node is still there).


Solution

  • Your need to pass the address of head for your function to modify it. Then your function needs to dereference this address. Further, the last pop() needs to change *AddressOfHead as well

    Node *pop(Node **AddressOfHead) {
        Node *temp = *AddressOfHead;
        if (temp) {
            *AddressOfHead = temp->next;
        }
        return temp;
    }
    

    ...

    // Usage example
    Node *TopOfList = pop(&Head);