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

如何修复无视索引参数的双向链表单函数插入功能

双向链表插入函数问题修复方案

核心问题梳理

你的代码存在以下几处导致索引不生效的错误:

  • 未处理index <= 1的头部插入场景:无论传入的索引值多小,都不会更新头指针,默认在头节点后插入元素
  • 存在无效内存泄漏:给temp指针提前申请的堆内存未使用也未释放,属于无效代码
  • 插入逻辑不完整:没有处理插入位置原后继节点的prev指针,中间插入会导致链表断裂
  • 强行截断链表:插入新节点时直接将new->next设为NULL,无论插入位置是否在链表中间,都会直接丢弃后半段链表,只有末尾追加的效果
  • 边界逻辑错误:当index为1时,循环条件i < (index-1)即i<0永远不成立,直接在头节点后插入,不符合头部插入预期

修正后代码

node *add(node *head, int index, int val)
{
    node *new = create(val);
    node *temp;
    // 空链表直接返回新节点作为头
    if (head == NULL)
    {
        new->prev = NULL;
        new->next = NULL;
        return new;
    }
    // 处理头部插入场景
    if (index <= 1)
    {
        new->next = head;
        head->prev = new;
        new->prev = NULL;
        return new;
    }
    // 遍历到目标位置的前一个节点
    temp = head;
    int i = 1;
    while (i < index - 1 && temp->next != NULL)
    {
        i++;
        temp = temp->next;
    }
    // 完成双向链表节点插入逻辑
    new->prev = temp;
    new->next = temp->next;
    // 如果不是末尾插入,更新原后继节点的前驱指针
    if (temp->next != NULL)
    {
        temp->next->prev = new;
    }
    temp->next = new;
    return head;
}

内容的提问来源于stack exchange,提问作者Saksh-BuiltABot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:54:07