尝试做一个简单的链表程序,得到段错误(核心转储)错误,任何人都可以帮助解决这个问题。无法理解指针到底在哪里搞砸了。
你能建议任何其他有效的方法来写这个吗
#include<iostream>
using namespace std;
struct node{
int x;
node *next;
}*head=NULL,*temp=head;
class list{
public:
list(){
temp=head;
}
//is something happening here causing core dump?
void addnode(int value){
if (head==NULL)
{
head->x=value;
head->next=NULL;
}
else
{
while(temp->next!=NULL)
temp=temp->next;
temp->next=new node;
temp=temp->next;
temp->x=value;
temp->next=NULL;
}
}
void print(){
while (temp->next!=NULL)
{
cout<<temp->x<<" ";
temp=temp->next;
}
}
};
int main()
{
list l=list();
l.addnode(12);
l.addnode(23);
l.print();
return 0;
}
你忘了分配对象
void addnode(int value){
if (head==NULL)
{
head = new node; //here was a mistake
head->x=value;
head->next=NULL;
同时删除全局临时变量并使用本地
else
{
node *temp = head;
while(temp->next!=NULL)
temp=temp->next;
}
void print(){
node *temp = head;
while (temp!=NULL) // here mistake too
{
cout<<temp->x<<" ";
temp=temp->next;
}
}
我是一名优秀的程序员,十分优秀!