【问题标题】:Why am I getting an AttributeError when trying to traverse a linked list?为什么在尝试遍历链表时会收到 AttributeError?
【发布时间】:2023-03-10 22:48:01
【问题描述】:

我正在尝试编写一个 search() 函数来在链表中搜索具有请求值的节点并返回该节点。

下面是我的代码:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def to_list(self):
        out = []
        node = self.head
        while node:
            out.append(node.value)
            node = node.next
        return out

    def search(self, value):
        """ Search the linked list for a node with the requested value  and return the node. """
        # Traverse through the list until a number is found
        node = self.head
        print(node)
        while node != value:
            node = node.next
        return node

# Test search
linked_list = LinkedList()
linked_list.prepend(2) # Method not shown for brevity
linked_list.prepend(1)
linked_list.append(4) # Method not shown for brevity
linked_list.append(3)
linked_list.to_list()
assert linked_list.search(1).value == 1, f"list contents: {linked_list.to_list()}"
assert linked_list.search(4).value == 4, f"list contents: {linked_list.to_list()}"

运行此代码给我以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-58-d70897699f08> in <module>()
      6 linked_list.append(3)
      7 linked_list.to_list()
----> 8 assert linked_list.search(1).value == 1, f"list contents: {linked_list.to_list()}"
      9 assert linked_list.search(4).value == 4, f"list contents: {linked_list.to_list()}"

<ipython-input-54-c7f29bb4a2be> in search(self, value)
      5     print(node)
      6     while node != value:
----> 7         node = node.next
      8     return node
      9 

AttributeError: 'NoneType' object has no attribute 'next'

谁能指出我为什么会收到这个 AttributeError?在 to_list 方法中使用了非常相似的遍历代码,所以我不确定为什么我在搜索方法中遇到这个问题。

【问题讨论】:

  • 看来你可能走到了尽头? node.next 变为 none,所以你尝试访问 None.next 是不可能的?
  • 提示:用self.head = Node(0)而不是self.head = None表示一个空列表。现在所有其他方法都可以假设self.head.next 指的是列表的头部(如果有的话),而不是必须迎合self.headNodeNone。虚拟节点可用于存储有关列表的元数据(例如长度)。

标签: python linked-list


【解决方案1】:

文本while node != value 完全错误。 node 变量应包含 Node 对象或 None。由于没有节点对象可以是 integer 1(即使它的 value 属性可以),您以 None 结尾并引发错误。

你想要的是:

while node and (node.value != value):
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2015-10-24
    • 2019-10-16
    • 2019-08-11
    相关资源
    最近更新 更多