【发布时间】:2019-05-18 16:41:37
【问题描述】:
在头节点中输入值时它可以工作,但是在创建中间节点时它会出现分段错误。我应该做些什么改变?
尝试进行各种更改还尝试通过查看 NULL 实例来消除分段错误,但失败了。如果这个问题看起来很愚蠢,请见谅,但我真的很努力。
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next;
};
node *head,*pre,*curr,*tail;
void createhead(int roll)
{
head->data=roll; //creating head
head->next=NULL;
pre=head;
}
void createlist(int roll)
{
curr->data=roll; //creating new node
curr->next=NULL; //in this two lines.
pre->next=curr;
pre=curr;
}
void disp()
{
curr=head;
while(curr!=NULL)
{
cout<<"Value---- \t"<<curr->data<<"\n";
curr=curr->next;
}
}
int main()
{
head =new node();
pre=new node();
tail=new node();
cout<<"Enter 999 to stop\n";
int roll;
cout<<"enter roll number\n";
cin>>roll;
if(roll!=999)
createhead(roll);
for(;;)
{
cout<<"enter roll number\n";
cin>>roll;
if(roll==999)break;
createlist(roll);
}
disp();
}
期望创建一个完整的链表。
【问题讨论】:
-
你似乎在给
cur赋值之前使用了它。 -
您的节点的
next指针似乎未初始化,因此您不应期望使用它们会得到任何合理的结果。 -
尝试进行各种更改 -- 这不是调试程序的方法。您应该首先查明问题所在,然后在确定问题后然后调整代码。只是随机更改代码,希望事情只是“工作”不是解决问题的方法。此外,很明显
curr是nullptr——您甚至在使用它的行上有注释。所以你没有检查那行来确保curr不是nullptr? -
有两件事使链表更易于管理: 1. 绘制图片以帮助您可视化列表的外观,并尝试按照您的编码说明绘制相同的图片。当您无法绘制相同的图片时,您就发现了一个错误。 2. 开发环境中应该有的调试工具。自 1980 年代以来,每个值得使用的开发环境都有一个调试器。如果你的没有,那就扔掉那一袋
并得到一个。
标签: c++ linked-list segmentation-fault