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

C++实现链表尾插元素时报segmentation fault错误如何解决

问题根因排查
  • 核心错误出现在insertion函数中处理中间/尾部插入的while循环条件顺序错误:C/C++逻辑与&&运算符遵循短路求值规则,原代码先写了item >= temp->next->data,当temp已经指向链表最后一个节点时,temp->next为NULL,此时直接访问temp->next->data就会触发空指针访问,导致段错误。
  • 次要问题:代码定义了双向链表的back指针,但全程没有对back指针赋值,后续如果要做反向遍历或者删除操作会有潜在问题。
修复方案

把while循环的两个条件交换顺序,先判断temp->next != NULL,确认非空后再访问temp->next->data即可解决段错误:

// 原错误代码
// while(item >= temp->next->data && temp->next != NULL)
// 修正后代码
while(temp->next != NULL && item >= temp->next->data)
完整修正后的可运行代码
#include <iostream>
using namespace std;

struct list
{
    int data;
    list *next,*back;
};

typedef struct list node;

node *start = NULL;

void display()
{
    node *temp;
    temp = start;

    while (temp!=NULL)
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}

void insertion(int item)
{
    node *temp,*temp2;

    if(start == NULL)
    {
        start = new node();
        start->data = item;
        start->next = NULL;
        start->back = NULL; // 补充back指针初始化
    }

    else if(item <= start->data)
    {
        temp = new node();
        temp->data = item;
        temp->next = start;
        start->back = temp; // 补充原头节点的back指向新头节点
        start = temp;
        start->back = NULL; // 新头节点的back置空
    }
    else // 插入中间和末尾的逻辑
    {
        temp = start;
        // 修正条件顺序,先判断非空再访问成员
        while(temp->next != NULL && item >= temp->next->data)
        {
            temp = temp->next;
        }

        temp2 = new node();
        temp2->data = item;
        temp2->next = temp->next;
        if(temp->next != NULL) {
            temp->next->back = temp2; // 补充后继节点的back赋值
        }
        temp2->back = temp;
        temp->next = temp2;
    }
}

void deletion()
{

}

void showMenu()
{
    cout << "0.Exit\n1.ShowMenu\n2.Insert\n3.Delete\n4.Display" << endl;
}

int main()
{
    showMenu();
    int choice;
    cout <<"Enter your Choice " << endl;
    cin >> choice;

    while(choice != 0)
    {
        if(choice == 1)
        {
            showMenu();
        }
        else if(choice == 2)
        {
            int item;
            cout << "Enter your item " << endl;
            cin >> item;
            insertion(item);
        }
        else if(choice == 3)
        {
            deletion();
        }
        else if(choice == 4)
        {
            display();
        }
        else
        {
            choice = 0;
        }

        cout <<"Enter your Choice " << endl;
        cin >> choice;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Efty Shan Abid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:45:09