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

为何以下C语言单链表程序无法打印链表?求助排查逻辑错误

单链表程序崩溃问题分析与修复

你的程序无编译错误但运行崩溃、无法输出,核心问题出在insert_end和insert_whenever函数,而非print_list,以下是具体问题和修复方案:

1. insert_end函数:访问NULL指针导致崩溃

在insert_end的else分支中,循环条件错误:

while(find!=NULL){
  find=find->next_generation;
}
find->next_generation=next_gen;

这个循环会让find一直走到链表末尾的NULL节点,此时对find->next_generation赋值属于对NULL指针解引用,直接触发程序崩溃。

修复代码:
将循环条件改为判断find->next_generation是否为NULL,让find停在最后一个有效节点:

void insert_end(int x){
    person*next_gen=(person*) malloc(sizeof(person));
    next_gen->age=x;
    next_gen->next_generation=NULL;

    if(head==NULL)
        head=next_gen;
    else{
        struct person*find=head;
        // 循环到最后一个节点(而非NULL)
        while(find->next_generation != NULL){
            find=find->next_generation;
        }
        find->next_generation=next_gen;
    }
}

2. insert_whenever函数:逻辑错误导致环结构

当前插入逻辑会形成循环链表,导致遍历死循环:

next_gen->next_generation=p;
p->next_generation=next_gen;

这段代码让新节点指向p,同时p指向新节点,形成环,后续print_list遍历会无限循环(不过程序在执行到这一步前已经因insert_end崩溃)。

修复代码:
正确的插入逻辑应该先让新节点接管p的后继,再让p指向新节点:

void insert_whenever(int x,person*p,int position){
    // 先检查p是否为NULL,避免非法访问
    if(p == NULL) return;

    person*next_gen=(person*)malloc(sizeof(person));
    next_gen->age=x;
    int i=1;
    // 循环到目标位置的前一个节点(或检查是否越界)
    while(i<position && p->next_generation != NULL){
        p=p->next_generation;
        i++;
    }
    // 先接后继,再挂到p上
    next_gen->next_generation = p->next_generation;
    p->next_generation=next_gen;
}

同时添加了越界检查,避免p变为NULL后访问其成员。

3. print_list函数:格式优化(可选)

当前输出的元素会连在一起,建议添加分隔符提升可读性:

void print_list(person *p){
    printf("[");
    while(p!=NULL){
        printf("%d",p->age);
        // 如果不是最后一个元素,添加逗号分隔
        if(p->next_generation != NULL){
            printf(", ");
        }
        p=p->next_generation;
    }
    printf("]\n"); // 加换行符,让输出更整洁
}

修复后运行程序,输出应为:[75, 45, 32, 12]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:19:56