我试图键入一个函数来在单链表的末尾添加一个节点,但不起作用

I tried to type a function to add a node at the end of a singlylinked list but is doesn't work

本文关键字:一个 添加 不起作用 链表 节点 函数 单链表      更新时间:2023-10-16

i键入该函数以在单链接列表的末尾添加节点。但行不通。

我尝试使用if否则显示1个节点,当列表为空时(按条件头= null(。它似乎有效。

void insert(int x)
 {
    node* temp=new node;
    node* n=head;
    temp->data=x;
    temp->next=NULL;
    while(n!=NULL)
    {
        n=n->next;
    }
    n->next=temp;
}

该程序正在显示分段故障。

这只是将您的新节点分配给本地变量n。它不会改变列表中的内容:

n=temp; 

这样做的有效方法是这样的:

void insert(int x)
{
    node** pp = &head;
    while (*pp)
        pp = &(*pp)->next;
    *pp = new node;
    (*pp)->data = x;
    (*pp)->next = nullptr;
}

这只需使用指针到列表中的列表中的指针。找到终止指针(如果列表为空并且head值为nullptr,则可以是head,如果不明显的是(,则将新节点分配并悬挂在适当的位置。这也可以在您的原始帖子中解决一个问题(将第一个节点挂在空列表上,带有null head(。