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

C语言单链表insertEnd尾插函数失效,运行始终输出空列表

问题根因分析

你的代码核心问题是C语言的函数值传递特性导致的:

  • main中定义的头指针l初始值为NULL,调用insertEnd时是把l的值(即NULL)复制给了函数形参l
  • 你在insertEnd内执行l=temp修改的只是局部形参副本,完全不会影响main里的原头指针,所以main中的l始终是NULL,display执行时自然输出Empty list
  • 代码还存在一个隐含bug:第一次传入l为NULL时,执行l=temp后p指向新节点,新节点的next本来就是NULL,后续执行p->next=temp会让节点的next指向自身形成环,如果头指针修改生效后续遍历会直接死循环
修复方案

有两种常用的修复方式:

方式1:让insertEnd返回新的头指针

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

struct node {
  int data;
  struct node *next;
};

// 函数返回头指针
struct node* insertEnd(struct node *l,int val) {
  struct node *temp=(struct node*)malloc(sizeof(struct node));
  temp->data=val;
  temp->next=NULL;
  // 原链表为空直接返回新节点作为头
  if (l==NULL) {
      return temp;
  }
  struct node* p=l;
  while (p->next!=NULL) p=p->next;
  p->next=temp;
  return l;
}

void display(struct node *l) {
  struct node *p=l;
  if (p==NULL) {
      printf("Empty list");
      return;
  }
  while (p!=NULL) {
    printf("%d ",p->data);
    p=p->next;
  }
}

int main() {
  struct node *l=NULL;
  // 调用时接收返回的头指针
  l = insertEnd(l,4);
  l = insertEnd(l,5);
  l = insertEnd(l,6);
  l = insertEnd(l,7);
  display(l);
  // 实际使用需补充链表内存释放逻辑,避免内存泄漏
  return 0;
}

方式2:传入头指针的二级指针

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

struct node {
  int data;
  struct node *next;
};

// 形参用二级指针接收头指针的地址
void insertEnd(struct node **l,int val) {
  struct node *temp=(struct node*)malloc(sizeof(struct node));
  temp->data=val;
  temp->next=NULL;
  // 原链表为空直接修改原头指针的值
  if (*l==NULL) {
      *l = temp;
      return;
  }
  struct node* p=*l;
  while (p->next!=NULL) p=p->next;
  p->next=temp;
}

void display(struct node *l) {
  struct node *p=l;
  if (p==NULL) {
      printf("Empty list");
      return;
  }
  while (p!=NULL) {
    printf("%d ",p->data);
    p=p->next;
  }
}

int main() {
  struct node *l=NULL;
  // 调用时传入头指针的地址
  insertEnd(&l,4);
  insertEnd(&l,5);
  insertEnd(&l,6);
  insertEnd(&l,7);
  display(l);
  // 实际使用需补充链表内存释放逻辑,避免内存泄漏
  return 0;
}

两种修复方式运行后都会正常输出4 5 6 7。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:15:04