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

Python循环单链表插入节点代码结果异常,求问题排查与修正

循环单链表插入功能修复说明

原有代码Bug汇总

  • 语法笔误:最终打印语句将实例名cll错写为call,直接运行会抛出未定义变量错误
  • 赋值逻辑错误:中间位置插入节点时,判断到插入位置为尾部的场景下,错误使用双等号==做比较而非单等号=给self.tail赋值,导致尾指针指向错误,是两个问题的核心诱因
  • 边界判断错误:中间位置插入的尾指针判断条件写错,应该判断新节点的下一个节点是否为self.head,而非原临时节点的下一个节点
  • 返回值位置错误:insertnode方法的返回语句只存在于else分支中,首次插入节点(链表为空场景)不会返回提示信息

修复后的完整代码

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
 
class CircularSLL:
    
    def __init__(self):
        self.head = None
        self.tail = None
        
    def __iter__(self):
        node = self.head
        while node:
            yield node
            if node.next == self.head:
                break
            node = node.next
            
    def insertnode(self, value, location):
        new_node = Node(value)
        
        # 链表为空的初始化场景
        if self.head is None:
            self.head = new_node
            self.tail = new_node
            new_node.next = self.head
            return '节点插入成功'
            
        # 插入到头部
        if location == 0:
            new_node.next = self.head
            self.head = new_node
            self.tail.next = self.head
        # 插入到尾部
        elif location == -1:
            new_node.next = self.tail.next
            self.tail.next = new_node
            self.tail = new_node
        # 插入到指定中间位置
        else:
            temp_node = self.head
            index = 0
            while index < location - 1:
                # 遍历到尾部就停止,避免死循环
                if temp_node.next == self.head:
                    break
                temp_node = temp_node.next
                index += 1
            next_node = temp_node.next
            temp_node.next = new_node
            new_node.next = next_node
            # 如果新节点插在尾部,更新尾指针
            if new_node.next == self.head:
                self.tail = new_node
        return '节点插入成功'
 
# 测试代码
cll = CircularSLL()
cll.insertnode(1,0)
cll.insertnode(3, 1)
cll.insertnode(4, 2)
cll.insertnode(5, 3)
cll.insertnode(6, 4)
print([node.value for node in cll]) 

# 测试头部插入
cll.insertnode(10,0)
print([node.value for node in cll]) 

# 测试尾部插入
cll.insertnode(30, -1)
print([node.value for node in cll]) 

修复验证结果

运行修复后的代码可得到完全符合预期的输出:

  1. 初始化插入后输出:[1, 3, 4, 5, 6]
  2. 头部插入10后输出:[10, 1, 3, 4, 5, 6]
  3. 尾部插入30后输出:[10, 1, 3, 4, 5, 6, 30]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:57:01