我知道这里有很多问题是基于在 C++ 中转储的分段错误核心,但我无法解决此错误。我的代码很容易创建链接列表并打印它。我想知道为什么它是错误的,因为我是这个主题的新手,想了解更多信息以及它是如何工作的以及错误意味着什么。
代码如下:
using namespace std;
struct node
{
int data;
node *next;
};
node *head =NULL;
void addnode(int x)
{
node *temp =new node;
temp->data = x;
temp ->next = NULL;
if(head==NULL)
{
head = temp;
}
else
{
node *p =head;
while(p!=NULL)
{
p=p->next;
}
p->next =temp;
temp =NULL;
}
}
void display(node *head)
{
node *temp=new node;
temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" , ";
temp = temp->next;
}
cout<<endl;
}
int main()
{
cout<<"Hello World";
node work;
addnode(12);
addnode(11);
addnode(1);
addnode(22);
display(head);
return 0;
}
很可能我弄乱了头指针,这就是为什么会发生这样的错误,但我想知道我的代码在这里做错了什么。
谢谢。非常感激 。
用于
while(p!=NULL)
{
p=p->next;
}
p->next =temp;
是个问题。当循环中断时,p
是一个 NULL 指针。之后,p->next
就不好说了。您需要使用:
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句