我试图键入一个函数来在单链表的末尾添加一个节点,但不起作用
I tried to type a function to add a node at the end of a singlylinked list but is doesn't work
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
(。
相关文章:
- 如何仅为一个函数添加延迟
- 使用std::transform将一个范围的元素添加到另一个范围中
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 为什么我必须添加一个小数才能在C++中正确计算此数学
- 尝试将另一个子句添加到代码中时出错
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 在单链表前面添加一个节点后,我无法遍历每个节点
- 为什么 QXmlQuery 似乎在结果中添加了一个""?(以及如何解决它?
- C++将带有重载构造函数的对象添加到另一个对象
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- c++:运行一个函数 8 次,并将每个答案添加到数组或 JSON 中
- 在多维向量中的特定位置添加一个值
- c ++ 我的 char* 数组被最后一个添加的元素覆盖
- 编写一个添加两个矩阵的函数
- 我正在尝试为 c++ 中的数组创建一个添加函数