如何从链表中弹出?

Tra*_*v92 5 c pointers return linked-list

我已经在C语言中用Pop函数实现了一个链表:

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;
}
Run Code Online (Sandbox Code Playgroud)

当我弹出时的输出将是这样的:

Temp is: node1 value
Temp is: node2 value
Run Code Online (Sandbox Code Playgroud)

也就是说,当我分配时,temp正在变为temp-> next *head = *head->next

那么,如何head在将Linked-list的头部移至的同时获取电流的值并返回呢head->next

这样head = head->next做不会删除对第一个节点的引用。(即,当我打印列表时,第一个节点仍然存在)。

chu*_*ica 2

head您需要传递函数的地址来修改它。然后你的函数需要取消引用这个地址。此外,最后一个 pop() 也需要更改 *AddressOfHead

Node *pop(Node **AddressOfHead) {
    Node *temp = *AddressOfHead;
    if (temp) {
        *AddressOfHead = temp->next;
    }
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

...

// Usage example
Node *TopOfList = pop(&Head);
Run Code Online (Sandbox Code Playgroud)