python - Python 中的链表实现错误

标签 python singly-linked-list

所以我试图在 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/

相关文章:

java - 使用 LinkedList 对名称进行排序并将它们存储到数组单元格中

c++ - 在 C++ 中显示链接列表的永无止境循环

python - 将 [0-255] 整数范围转换为 [0.0-1.0] 浮点范围

python - 未从 PyPDF2 上的正则表达式接收 PDF 的正确模式

c - 双指针向链表添加元素

algorithm - 您将如何从单向链表(一次遍历)中的尾部获取第 n 个节点?

ruby - 没有扩展数组的 ruby​​ 中最好的链表?

python - 有条件地创建(填充)一列,该列必须处理数据框中的行以匹配条件

python - 将 numpy.ndarray 转换为字符串

python - 平铺 block 在 pygame 平台游戏中渲染不可见