嗨,我正在尝试通过完成第一个作业来学习 Python,即使用 Python 实现链接列表。我已经实现了所有其他功能。但是当尝试删除不存在的项目时,删除功能给了我错误。谁能帮我?非常感谢。
我定义的删除函数:
def delete(self,item):
current = self.head
previous = None
found = False
while not found:
if current.get_data() == item:
found = True
else:
previous = current
current = current.get_next()
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
然后我编写了以下代码进行测试:
my_list = LinkedList()
my_list.add(31)
my_list.add(77)
my_list.add(17)
my_list.add(93)
my_list.add(26)
my_list.add(54)
assert my_list.size() == 6
my_list.delete(77)
my_list.delete(1)
assert my_list.size() == 5
print(my_list.__str__())
AttributeError:“NoneType”对象没有属性“get_data”
get_data() 是在 Node 类中定义的,我不知道为什么在尝试删除不存在的项时当前的局部变量会变成 NoneType 而不是 Node。谁能帮我?谢谢!
最佳答案
只有当您真正找到该元素时,循环才会停止。如果该元素不在列表中,则它会继续下去。据推测,get_next()
返回None
对于最后一个元素,因此在循环遍历列表中的所有元素之后 current
变成None
。下次循环时您调用 current.get_data()
,即不起作用,因为 current
是 None
和None
没有get_data
成员,就像错误消息所说的那样。
要解决这个问题,您需要在到达数组末尾时停止循环。您可以通过将 while 修改为
来做到这一点while current is not None and not found:
关于python - 使用Python实现链表删除功能时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28310627/