【发布时间】: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.head是Node或None。虚拟节点可用于存储有关列表的元数据(例如长度)。
标签: python linked-list