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

C语言单链表插入异常:仅显示首次插入元素的技术求助

单链表插入元素仅显示首元素的问题修复

问题根源

你的代码在insert函数的else分支存在两处关键错误:

  1. 遍历终止条件错误:原代码用while(ptr!=NULL)遍历,会让ptr最终指向NULL,此时无法将新节点链接到链表的最后一个节点上。正确的做法是遍历到最后一个节点(即ptr->next != NULL时停止)。
  2. 尾节点链接逻辑错误:原代码最后执行ptr=t,但ptr是函数的局部参数,修改它不会影响链表的实际结构。应该把最后一个节点的next指针指向新创建的节点t。
  3. 额外的冗余赋值:t->value=n在else分支重复设置,前面已经完成赋值,可删除。

修正后的代码

#include<stdio.h>
#include<stdlib.h>

struct node 
{
    int value;
    struct node *next;
}*first = NULL;

void insert(struct node *ptr,int n ){
    struct node* t;
    t=(struct node* )malloc(sizeof(struct node));
    t->value=n;
    t->next = NULL; // 显式置空,避免野指针
    
    if(first==NULL){
        first=t;
        return;
    }
    else{
        ptr=first;
        // 遍历到最后一个节点
        while(ptr->next != NULL){
            ptr=ptr->next;
        }
        // 将最后一个节点的next指向新节点
        ptr->next = t;
     }
}

void display(struct node *f){
    while(f!=NULL){
        printf("%d ",f->value); // 加空格分隔元素,可读性更好
        f=f->next;
    }
}

int main(){
    insert(first,5);
    insert(first,20);
    insert(first,32);
    insert(first,66);
    insert(first,689);
    display(first);
    return 0;
}

额外优化说明

  • 新增t->next = NULL:显式将新节点的next置空,避免malloc分配的内存中存在随机值导致的野指针问题。
  • display函数中添加空格:让输出的元素之间有分隔,更易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:05:44