Python中Linked List实现报错:'str'对象无nextNode属性
问题解决:链表实现中的AttributeError错误
错误原因
你初始化链表时犯了一个关键错误:ll = linkedList("10")直接将字符串"10"作为head传入,但linkedList的head属性应该是linkedListNode类的实例,而非原始值。这导致后续遍历链表时,currentNode是字符串类型,自然不存在nextNode属性,触发AttributeError。
修复方案
方案1:直接修正初始化代码
将链表初始化语句改为传入linkedListNode实例:
ll = linkedList(linkedListNode("10"))
方案2:优化链表构造函数(可选)
如果想让链表支持直接传入值作为head,可以修改linkedList的__init__方法,自动将传入的原始值转为节点:
class linkedList(): def __init__(self, head=None): # 如果传入的不是节点,自动转为节点 if head is not None and not isinstance(head, linkedListNode): self.head = linkedListNode(head) else: self.head = head
这样初始化时写ll = linkedList("10")就可以正常工作了。
完整修复后的代码(方案1版本)
class linkedListNode: def __init__(self, value, nextNode=None): self.value = value self.nextNode = nextNode class linkedList(): def __init__(self, head=None): self.head = head def insert(self, value): node = linkedListNode(value) if self.head is None: self.head = node return currentNode = self.head while True: if currentNode.nextNode is None: currentNode.nextNode = node break currentNode = currentNode.nextNode def printLinkedList(self): curNode = self.head while curNode is not None: print(curNode.value) curNode = curNode.nextNode # 测试代码 ll = linkedList(linkedListNode("10")) ll.insert("50") ll.insert(4) ll.insert(6) ll.insert(3) ll.insert(1) ll.printLinkedList()
内容的提问来源于stack exchange,提问作者max
相关产品推荐
相关产品推荐

