【问题标题】:Tried hard to remove segmentation fault but failed努力消除分段错误但失败了
【发布时间】:2019-05-18 16:41:37
【问题描述】:

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

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

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

【问题讨论】:

  • 你似乎在给cur赋值之前使用了它。
  • 您的节点的next 指针似乎未初始化,因此您不应期望使用它们会得到任何合理的结果。
  • 尝试进行各种更改 -- 这不是调试程序的方法。您应该首先查明问题所在,然后在确定问题后然后调整代码。只是随机更改代码,希望事情只是“工作”不是解决问题的方法。此外,很明显currnullptr——您甚至在使用它的行上有注释。所以你没有检查那行来确保curr 不是nullptr
  • 有两件事使链表更易于管理: 1. 绘制图片以帮助您可视化列表的外观,并尝试按照您的编码说明绘制相同的图片。当您无法绘制相同的图片时,您就发现了一个错误。 2. 开发环境中应该有的调试工具。自 1980 年代以来,每个值得使用的开发环境都有一个调试器。如果你的没有,那就扔掉那一袋 并得到一个。

标签: c++ linked-list segmentation-fault


【解决方案1】:

链表的想法是当你在链表的末端添加一个节点时,你会做两件事:

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

这是您的代码示例:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-06-30
    • 2014-01-05
    • 1970-01-01
    • 2015-01-20
    • 2016-06-13
    • 2018-08-14
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多