如何在 c++ 中删除链表的第一个节点

How to delete the first node of a linked list in c++

本文关键字:链表 第一个 节点 删除 c++      更新时间:2023-10-16

我一直在尝试从单个链表中删除第一个节点。我所做的如下

  • 创建指向头节点的临时节点
  • 将磁头移动到下一个节点
  • 释放临时节点并返回头部

生成一个简单的链表后: 1 - > 2 -> 3 -> 4 -> 5

并调用我删除第一个节点的方法,结果不正确。它返回以下链表:0 -> 2 -> 3 -> 4 -> 5

我不明白为什么0仍然存在。

#include <cstdlib>
#include <iostream>
using namespace std;
struct Node
{
    int data;
    struct Node *next;
};
Node* Delete(Node *head)
{
    Node* temp = head;
    head = head->next;
    delete temp;
    return head;
}
int main(void) {
    Node* head = new Node();
    Node*  temp = head;
    for(int i=1; i<=5; i++)
    {
        Node* newNode = new Node();
        newNode->data = i;
        newNode->next = NULL;
        temp->next = newNode;
        temp = newNode;
    }
    Delete( head = head->next );
    while(head != NULL)
    {
        cout<<head->data<<" ";
        head = head->next;
    }
    cout<<endl;     
   return 0;
}
您需要

更改调用Delete的方式。 它应该是

head = Delete ( head );

拥有代码的方式,你分配head head->next并在head->next上调用Delete

此外,删除的调用是错误的,你混合了新的和自由的来管理动态内存,正如人们之前所说的那样,你有一个 0 值,因为初始列表是 0 -> 1 -> 2 -> 3 -> 4 -> 5。您在没有任何初始值的情况下开始 head,并且对于该 head->data 为 0。

我想在这里强调两件事-

第一:你的代码在这里生成的链表是0->1->2->3->4->5

第二:通过查看您的代码,您似乎打算在链表的第二个节点(head->next)上调用 Delete,而不是在第一个节点(head)上调用 DELETE。

但是,您调用 Delete 的方式需要首先更正。所以,如果要删除链表的第一个节点(head),可以这样调用:

head = Delete(head);

你应该很高兴。输出将是:1->2->3->4->5(根据您首先创建的链接列表,这是正确的)

希望这有帮助。

我认为你可以用更简单的方式编写删除函数。例如,你可以这样写:

void Delete(nod * &p)
{
    nod * t = p -> urm;
    p = t;
}

我只想指出,我的母语不是英语,所以变量可能对你没有意义;解释如下:您将引用 p,因为它会改变元素会改变。p = 第一个元素;点头 = 节点;urm = next(是记忆第一个元素地址的指针)。希望我能帮到你!