链表的弹出方法行为异常

问题描述 投票:1回答:1

我有两个不同的链表,我尝试从第一个链表弹出一个节点,然后到第二个链表。调用pop函数(pop(Node * head))时,我的目标是更新新的头部并返回到弹出的节点。但是,发生的情况是它转到弹出的节点,但传递的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);
            }
c algorithm data-structures linked-list singly-linked-list
1个回答
0
投票

此功能

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);

其次,除了释放弹出的节点,您还可以将其返回,并将其数据成员设置为NULL。通常,头节点也可以等于NULL。

功能看起来像

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

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

    return current;
}
© www.soinside.com 2019 - 2024. All rights reserved.