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

Python链表add_at_index指定索引插入方法运行异常问题咨询

问题原因分析

核心错误:add_at_index方法逻辑错误

你找到前序节点后的赋值逻辑完全写反,且遗漏了插入的两个必要步骤:

  1. 你当前写的new_node = curr.next是把前序节点原来的下一个节点赋值给你刚创建的新节点,直接覆盖了新节点对象,没有任何插入动作,相当于直接丢弃了你要插入的节点
  2. 正确插入逻辑需要完成两步操作:
    • 先把新节点的next指针指向原前序节点的后继节点:new_node.next = curr.next
    • 再把前序节点的next指针指向新节点:curr.next = new_node
  3. 额外冗余问题:index==0的处理分支后没有加return,会导致后续的循环逻辑无意义执行。

其他隐藏bug

add_at_end方法赋值逻辑写反

空链表插入尾部的分支里,你写的new_node = self.head把空值赋值给了新节点,应该改为self.head = new_node,否则空链表无法正常插入尾部节点。

remove_at方法索引判断逻辑错误

你写的判断条件if index < 0 or index<= self.get_length()会导致所有合法索引都触发异常,正确的合法判断应该是if index < 0 or index >= self.get_length(),链表合法索引范围是0到长度-1。

add_at_index方法索引判断限制不合理

当前判断index >= self.get_length()不允许插入到链表末尾之后的位置(比如长度为3的链表插入到索引3,对应尾部插入),如果需要支持尾部插入可以把判断改为index > self.get_length()。


修正后的add_at_index参考代码:

def add_at_index(self,data,index):
    new_node = Node(data)
    # 允许插入到末尾的话修改判断条件为 index <0 or index>self.get_length()
    if index < 0 or index >= self.get_length():
        raise Exception("invalid input")
    if index == 0:
        new_node.next = self.head
        self.head = new_node
        return # 这里加return避免执行后续逻辑
    count = 0
    curr = self.head
    while curr is not None:
        if count == index-1:
            # 替换原来的错误赋值
            new_node.next = curr.next
            curr.next = new_node
            break
        curr = curr.next 
        count +=1 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:45:03