You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现有序单链表出现segmentation fault段错误如何解决?

问题排查与修复方案

核心问题原因

  • 链表遍历未做空指针校验:当插入的新元素大于链表所有已有元素时,temp指针会遍历到链表末尾的NULL,此时访问temp->info属于空指针访问,直接触发段错误。你之前修改的while (temp != NULL && newNode->info > temp->info)确实解决了遍历越界的问题,但还有其他逻辑漏洞导致异常。
  • 条件分支逻辑缺失:你没有处理新元素小于等于头节点值的场景,同时sort函数中的两个if是并列关系,没有用else分隔,会导致边界场景逻辑执行异常。
  • 未处理终止值插入:当你输入-1终止程序时,代码仍然会将-1传入sort函数尝试插入链表,属于逻辑冗余。

修复后的完整代码

#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 insertSorted(int input){
        node *newNode = new node (input);
        // 空链表直接插入
        if (isEmpty()){
            head = tail = newNode;
            return;
        }
        // 新元素小于等于头节点,直接插在头部
        if (newNode->info <= head->info) {
            newNode->next = head;
            head = newNode;
            return;
        }
        // 遍历找到合适的插入位置
        node *temp = head;
        // 提前预判下一个节点不为空,避免越界,同时直接拿到插入位置的前驱节点
        while (temp->next != NULL && newNode->info > temp->next->info) {
            temp = temp->next;
        }
        // 插入节点
        newNode->next = temp->next;
        temp->next = newNode;
        // 如果插在末尾,更新tail
        if (newNode->next == NULL) {
            tail = newNode;
        }
    }
};

int main () {
    osll l;
    int input = 0;
    while (true) {
        cout << "Enter a value: ";
        cin >> input;
        if (input == -1) {
            break;
        }
        l.insertSorted(input);
    }
    // 遍历打印验证结果,可按需删除
    node *p = l.head;
    cout << "排序后的链表:";
    while(p != NULL) {
        cout << p->info << " ";
        p = p->next;
    }
    cout << endl;
    return 0;
}

关键修改说明

  • 把函数名从sort改为insertSorted更符合功能定位,避免和标准库sort混淆
  • 拆分了不同插入场景的分支,每个分支处理完直接return,避免逻辑交叉
  • 遍历的时候判断temp->next != NULL,既避免空指针访问,也能直接拿到插入位置的前驱节点,简化插入逻辑
  • 输入-1的时候直接跳出循环,不会执行插入逻辑,避免无效插入
  • 补充了插入后tail指针的更新逻辑,保证链表属性正确

内容的提问来源于stack exchange,提问作者hjhbb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:06:04