在头节点中输入值时可以使用,但是在创建中间节点时会出现分段错误。我应该做些什么改变?
尝试进行各种更改还尝试通过查看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();
}
计划创建一个完整的链接列表。
答案 0 :(得分:0)
链接列表的想法是,当您在列表末尾添加一个节点时,您需要做两件事:
以下是您的代码示例:
void createlist(int roll)
{
// create a new node for the roll
curr = new node();
curr->data = roll;
// point the next node to the head of the list (adds it to the front)
curr->next = head;
// now curr is the head
head = curr;
}
可以使用类似的方法将商品附加到尾部。
在列表中间插入项目将需要索引到列表中,并将索引节点的下一个指针设置为指向新节点,并将新节点的下一个指针设置为指向索引节点的下一个指针