首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解决分段故障单链表?

如何解决分段故障单链表?
EN

Stack Overflow用户
提问于 2021-09-03 20:57:18
回答 1查看 65关注 0票数 0

编辑:我刚试着做while (temp != NULL && newNode->info > temp->info){,但由于某些原因还是不能工作,我试着输入5和4,但再次遇到分割错误

对于糟糕的代码,我很抱歉,我是个新手,我正在尝试创建一个排序的单链表。我不知道它有什么问题,如果有人能帮我解决这个问题,我会非常感激的。

我也许能够输入一些值,每次出于某种原因(不是因为我输入了-1),每次都有不同数量的值。然后它只会显示“发生了异常。分割错误。”在这一行,我不确定为什么,因为我比较的是值,而不是内存地址:

while (newNode->info > temp->info){

完整代码:

代码语言:javascript
复制
#include <iostream>
using namespace std;

class node {
public:
    int info;
    node *next;

    node (int data, node *ptr = 0) {
        info = data;
        next = ptr;
    }
};

class osll{

    public:
    node *head, *tail;

    osll(){
        head = tail = 0;
    }

    bool isEmpty(){
        return head == 0;
    }

    void sort(int input){

        node *newNode = new node (input);

        if (isEmpty()){
            newNode ->next = head;
            head = newNode;
            if (tail == 0)
                tail = head;
        }
        if (newNode ->info > head ->info){

            node *temp = head;
            while (newNode->info > temp->info){
                temp = temp ->next;
            }
            
            // will figure out how to link newNode to 
            // whatever temp value that stops here
            // once this error goes away
        }
    }

    
};



int main () {
    osll l;
    int input = 0;

    while (input != -1) {
        cout << "Enter a value: ";
        cin >> input;
        l.sort(input);
    }

    return 0;

}
EN

回答 1

Stack Overflow用户

发布于 2021-09-03 21:31:21

如果您的新数字是列表中的最大值,则会导致分段错误,因为您不会在while循环中检查是否到达了列表的末尾。在最后一个元素temp将为空之后,所以.temp->info将导致分段错误。

例如,您应该这样做(第40行)

代码语言:javascript
复制
while (temp != null && newNode->info > temp->info)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69050477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档