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

C语言自定义结构体链表的元素添加Add函数实现问题

C语言自定义链表Add添加函数的正确实现

现有代码的核心问题

  • 参数全为值传递:函数内修改的array和item都是实参的临时拷贝,函数返回后所有修改都不会作用到原链表;且&item取的是临时变量的地址,函数结束后成为野指针,会触发内存访问错误
  • 尾插逻辑错误:遍历到最后一个节点后,没有给最后一个节点的next赋值,而是直接修改头节点的next,会丢失原有链表的后续节点
  • 未处理空链表等边界异常场景

修正后的完整代码

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

typedef struct Liste Liste;
struct Liste{
    double c;
    int n;
    Liste* next; // 指向链表下一个元素
};

// 参数1:链表头节点指针,保证修改能作用到原链表;参数2:待添加新节点的指针
void Add(Liste* head, Liste* new_item) {
    // 边界异常处理
    if (head == NULL || new_item == NULL) {
        return;
    }
    // 遍历找到链表最后一个节点
    Liste* last = head;
    while (last->next != NULL) {
        last = last->next;
    }
    // 挂载新节点
    last->next = new_item;
    new_item->next = NULL;
    printf("新节点地址:%p\n", new_item);
}

int main(){
    Liste array = {12.4, 4, NULL};
    printf("头节点c值:%f\n", array.c);
    Liste item = {15.4, 7, NULL};
    // 传地址保证函数内修改生效
    Add(&array, &item);
    printf("头节点的next地址:%p\n", array.next);
    // 验证添加结果
    if (array.next != NULL) {
        printf("新节点c值:%f,n值:%d\n", array.next->c, array.next->n);
    }
    return 0;
}

动态分配节点版本(可选)

如果不需要提前在栈上定义节点,可以直接在Add函数内完成内存分配,避免临时变量生命周期问题:

void AddDynamic(Liste* head, double c_val, int n_val) {
    if (head == NULL) return;
    // 动态申请新节点内存
    Liste* new_item = (Liste*)malloc(sizeof(Liste));
    if (new_item == NULL) {
        perror("内存申请失败");
        return;
    }
    new_item->c = c_val;
    new_item->n = n_val;
    new_item->next = NULL;
    // 挂载到链表尾部
    Liste* last = head;
    while (last->next != NULL) {
        last = last->next;
    }
    last->next = new_item;
}

使用该版本注意程序退出前要遍历链表调用free释放所有动态申请的内存,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:06:02