c++ - 努力消除分段错误但失败了
问题描述
在头节点中输入值时它可以工作,但是在创建中间节点时会出现分段错误。我应该做些什么改变?
尝试进行各种更改还尝试通过查看 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();
}
期望创建一个完整的链表。
解决方案
链表的想法是,当您将节点添加到列表的末尾时,您会做两件事:
- 创建一个新项目
- 将项目插入列表
- 将插入的节点重新分配为头
这是您的代码示例:
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;
}
可以使用类似的方法将项目附加到尾部。
在列表中间插入一个项目需要对列表进行索引,并将索引节点的下一个指针设置为指向新节点,并将新节点的下一个指针设置为指向索引节点的下一个指针。
推荐阅读
- python - 如何使python脚本运行或目录中的所有文件?
- remark42 - 如何在没有社交登录的情况下以管理员身份登录 remark42 评论系统
- excel - 如何粘贴数据一定次数
- javascript - require.context 的 tsx 和 jsx 文件
- javascript - 我怎样才能去,通过按下反应中的按钮,铬扩展被重定向到另一个组件?
- node.js - 错误:使用电子包装器进行电子包装
- flutter - 在小部件中定义成员时如何避免警告?
- javascript - 为临时链接添加过期时间
- python - 数据集中的大多数记录被分配到一个集群 - kmeans clustering
- c++ - SDL_SetWindowSize 调整大小后,绘制完成偏移屏幕