所以我试图在 python 中创建一个链接列表,但我收到此错误:
If currentNode.nextNode is None:
AttributeError: 'str' object has no attribute 'nextNode'
不知道为什么我认为 currentNode.nextNode
应该有一个 .nextNode
属性,就像所有其他节点一样。
代码如下:
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==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!=None:
print(curNode.value)
curNode=curNode.nextNode
#Just testing out the linked list below to see if it works:
ll=linkedList("10")
ll.insert("50")
ll.insert(4)
ll.insert(6)
ll.insert(3)
ll.insert(1)
ll.printLinkedList()
最佳答案
按照您定义 linkedList
的方式,它需要 linkListNode
的实例作为参数,而不是值。
ll = linkedList(linkedListNode("10"))
关于python - Python 中的链表实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74881571/