链表的 Pop 方法行为异常

Pop method for linked list behaves unexpectedly

我有两个不同的链表,我尝试从第一个链表弹出一个节点到第二个链表。我在调用 pop 函数 (pop(Node * head)) 时的目标是更新新的 head 和 return 到弹出的节点。但是,发生的情况是它转向弹出的节点,但传递的 Node * head 指向弹出的元素。因此我无法继续。这个功能有什么问题?我可能搞砸了指针

Node * pop(Node * head)
{
    Node * temp = head;
    long val = temp -> value; //store the value before deallocating

    head = head -> next;
    free(temp);
    return createNode(val);
}

//Code snippet where I call the pop function
if (currNode == NULL) {
                headSublistPointers -> node = pop(tmpHeadOrigArr);
            } else {
                while (currNode -> next != NULL) {
                    currNode = currNode -> next; //go until the end of the linked list
                }
                currNode -> next = pop(tmpHeadOrigArr);
            }

这个函数

Node * pop(Node * head)
{
    Node * temp = head;
    long val = temp -> value; //store the value before deallocating

    head = head -> next;
    free(temp);
    return createNode(val);
}

没有意义。

对于初学者,头部应通过引用传递

Node * pop(Node **head);

其次,您可以 return 将其数据成员设置为 NULL,而不是释放弹出的节点。同样一般头节点可以等于NULL。

函数看起来像

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

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

    return current;
}