首页 > 解决方案 > 努力消除分段错误但失败了

问题描述

在头节点中输入值时它可以工作,但是在创建中间节点时会出现分段错误。我应该做些什么改变?

尝试进行各种更改还尝试通过查看 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();
}

期望创建一个完整的链表。

标签: c++linked-listsegmentation-fault

解决方案


链表的想法是,当您将节点添加到列表的末尾时,您会做两件事:

  • 创建一个新项目
  • 将项目插入列表
  • 将插入的节点重新分配为头

在此处输入图像描述

这是您的代码示例:

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;
}

可以使用类似的方法将项目附加到尾部。

在列表中间插入一个项目需要对列表进行索引,并将索引节点的下一个指针设置为指向新节点,并将新节点的下一个指针设置为指向索引节点的下一个指针。

在此处输入图像描述


推荐阅读