Python链表代码报错:'Node'对象不可调用问题求助
问题排查与解决:TypeError: 'Node' object is not callable in Linked List Implementation
嘿,我来帮你搞定这个链表实现里的错误!咱们一步步来拆解问题:
直接触发报错的原因
你在printlist方法里写了一行错误的代码:
printval(printval.item)
这里的printval是一个Node类的实例对象,结果你把它当成函数来调用了——这就是TypeError: 'Node' object is not callable的根源。你真正想做的是用Python内置的print()函数输出节点的item值,所以应该改成:
print(printval.item)
容易忽略的隐藏Bug
除了上面的笔误,你的Node类构造函数还有逻辑颠倒的问题:
def __init__(self,item): self.item = None self.next = item
这里你把传入的节点值item错误地赋值给了next指针,反而把存储数据的self.item设成了None,这会导致所有节点的实际数据都丢失,就算你修正了上面的打印问题,输出的也全是None。正确的写法应该是:
def __init__(self, item): self.item = item # 把传入的数据存到item属性 self.next = None # 初始化next指针为空
修正后的完整代码
把这两处错误都修复后,完整的可运行代码如下:
# Linked List class Node: def __init__(self, item): self.item = item self.next = None class Linked: def __init__(self): self.head = None def printlist(self): printval = self.head while printval is not None: print(printval.item) printval = printval.next def insertion(self, newitem): NewNode = Node(newitem) NewNode.next = self.head self.head = NewNode def InsertBetween(self, Middle_Node, newitem): if Middle_Node is None: print("Value doesn't exist in node") return NewNode = Node(newitem) NewNode.next = Middle_Node.next Middle_Node.next = NewNode listy = Linked() listy.head = Node(20) p2 = Node(21) p3 = Node(22) listy.head.next = p2 p2.next = p3 listy.InsertBetween(listy.head.next, 40) listy.insertion(45) listy.printlist()
运行结果
执行这段代码后,你会得到预期的输出:
45 20 21 40 22
内容的提问来源于stack exchange,提问作者Tanishq
相关产品推荐
相关产品推荐

