Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 删除线性链表的第一个节点_C++_Linked List - Fatal编程技术网

C++ 删除线性链表的第一个节点

C++ 删除线性链表的第一个节点,c++,linked-list,C++,Linked List,我遇到了以下用于删除链接列表第一个节点的代码: Node* removeFirstNode(struct Node* head) { if (head == NULL) return NULL; // Move the head pointer to the next node Node* temp = head; head = head->next; delete temp; return head; }

我遇到了以下用于删除链接列表第一个节点的代码:

Node* removeFirstNode(struct Node* head)
{
    if (head == NULL)
        return NULL;
  
    // Move the head pointer to the next node
    Node* temp = head;
    head = head->next;
  
    delete temp;
  
    return head;
}
谁能给我解释一下:

  • 使用temp变量的意义,即我们是否可以在不使用temp变量的情况下使用此代码
  • 2.作业头=作业头->下一步做什么

  • head和temp之间的关系是什么,即temp是指向head的指针吗

  • head也是指向链表第一个节点的指针吗

  • 若第三部分和第四部分的答案都是肯定的,那个么temp不是变成了一个双指针(指向指针的指针)

  • 需要
    temp
    指针,因为在重新分配
    head
    后,需要使用
    delete
    释放链表中第一个节点的内存。这可以防止在调用函数时发生错误

  • 分配
    head=head->next
    将链表的开头移动到第二个节点,然后删除第一个节点

  • 赋值
    Node*temp=head
    使
    temp
    指向与
    head
    相同的地址,但在重新赋值
    head
    后(参见第2点),指针不再指向相同的地址

  • 是,
    head
    是指向链表开头的指针

  • 没有
    temp
    不是
    Node**
    类型,但是
    head
    被重新分配(参见第3点)


  • 回答得很好,但我无法理解第五部分,即为什么temp从来都不是“Node**”类型。另外,不使用temp指针是否可以释放磁头的内存?@proglove为什么
    temp
    应该是
    Node**
    类型?请解释一下你认为它是双指针的理由。那么我就更容易解释原因,为什么它不是
    Node**
    @proglove类型,以及关于你的第二条评论。如果没有
    temp
    ,我不认为有一种简单的方法可以释放第一个节点的内存,但我会让你知道,如果我将来偶然发现一种更简单的方法。因为temp指向head,head指向链表的第一个元素,因此我认为它应该是一个双指针。