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

C语言链表插入节点时索引≥2丢失首节点问题求助

C语言链表指定索引插入时索引≥2丢失首节点的原因及修复

问题根源

问题出在insert_at函数的遍历逻辑中,你直接修改了链表的头指针:

while((*list) != NULL){
    i++; 
    if (i == index){
        // 插入逻辑
        return 1;
    }
    (*list) =(*list)->next; // 此处直接修改了链表的头指针变量
}

因为List是Node**类型,*list就是链表的头节点指针。当插入索引≥2时,循环会不断将*list指向后续节点,遍历结束后,原来的头节点地址被覆盖,导致链表首节点永久丢失。

举个例子,第二次插入索引2时:

  • 初始*list指向"Zero"节点
  • 第一次循环:i变为1,不满足索引条件,*list被修改为指向"One"节点
  • 第二次循环:i变为2,执行插入操作,但此时链表头指针已经指向"One",原首节点"Zero"彻底丢失

修复方案

使用临时指针遍历链表,避免修改头指针本身:

修改后的insert_at函数:

int insert_at(List list,int index,char *value){
    if ((index > 0 && is_empty(list) == 1) || index < 0){
        return 0;
    }
    if (index == 0){
        add(list, value);
        return 1;
    }
  
    Node *curr = *list; // 用临时指针curr遍历,不改动头指针
    int i = 0;
    while(curr != NULL){
        i++; 
        if (i == index){
            Node *node = new_node(value);
            node->next = curr->next;
            curr->next = node;
            return 1;
        }
        curr = curr->next; // 移动临时指针而非头指针
    }
    return 0;
}

另外补充一个潜在问题修正:new_list函数中malloc(sizeof(List))应该改为malloc(sizeof(Node*)),因为List是指针类型,直接用它的大小可能导致内存分配不足:

List new_list(){
    List list = malloc(sizeof(Node*)); // 修正为Node*的内存大小
    *list = NULL;
    return list;
}

修复后输出验证

运行原主函数,输出会变为:

["Zero", "Two", "Three"]
Inserting at 1 
["Zero", "one", "Two", "Three"]
Inserting at 2 
["Zero", "one", "inserted", "Two", "Three"]

首节点不再丢失,插入逻辑正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:25:41