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

单链表指定位置节点移除函数异常求助:非头节点均提示越界

单链表removeAt函数问题修复

问题分析

你的代码存在三个关键错误,导致除头节点外的有效位置操作异常:

  1. 节点总数未更新:删除节点后没有将count减1,后续位置检查会基于旧的节点总数,误判有效位置为超出范围。
  2. 头节点处理的赋值错误:last == NULL是比较操作而非赋值,删除最后一个节点时last无法正确置空。
  3. 删除对象错误:非头节点删除时,代码删除了前驱节点current,而非目标节点trailCurrent,破坏链表结构同时造成内存泄漏。

修复后的代码

template<class Type>
void linkedListType<Type>::removeAt(int location)
{
    nodeType<Type> *current;
    nodeType<Type> *trailCurrent;
    current = first;
    int counter;

    if (location < 0 || location >= count)
    {
        cout << "location out of range\n";
        return; // 提前返回,避免执行后续逻辑
    }
    else if(location == 0)
    {
        first = first->link;
        if (first == NULL)
            last = NULL; // 修正为赋值操作
        delete current;
        count--; // 更新节点总数
    }
    else 
    {
        counter = 0;
   
        while (counter != location - 1)
        {
            current = current->link;
            counter++;
        }

        trailCurrent = current->link;
        current->link = trailCurrent->link;
        // 若删除的是最后一个节点,更新last指针
        if (trailCurrent == last)
            last = current;
        delete trailCurrent; // 修正为删除目标节点
        count--; // 更新节点总数
    }
}

额外说明

  • 位置超出范围的分支添加return,避免后续无关逻辑执行。
  • 每次删除节点后必须执行count--,保证链表节点总数的准确性,这是解决“有效位置提示超出范围”的核心。
  • 非头节点删除时,若目标节点是最后一个,需同步更新last指针,避免指针指向已释放的内存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:55:35