使用Python实现链表删除函数时出错
嗨,我正试图通过做第一个作业来学习Python,这是用Python实现一个链表。我已经实现了所有其他功能。但delete函数在尝试删除不存在的项时出错。有人能帮我吗?非常感谢 我定义的删除函数:使用Python实现链表删除函数时出错,python,linked-list,Python,Linked List,嗨,我正试图通过做第一个作业来学习Python,这是用Python实现一个链表。我已经实现了所有其他功能。但delete函数在尝试删除不存在的项时出错。有人能帮我吗?非常感谢 我定义的删除函数: def delete(self,item): current = self.head previous = None found = False while not found: if current.get_d
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:“非类型”对象没有属性“获取数据”
get_data()是在Node类中定义的,我不知道为什么在尝试删除不存在的项时,当前局部变量会变为NoneType而不是Node。有人能帮我吗?谢谢大家! 当您处于循环中时,在尝试访问其数据之前,需要确保
当前
不是无
。我认为处理这个问题的最简单方法是,如果None
,只需返回
while not found:
if current is None:
return
# rest of loop
只有在实际找到元素时,循环才会停止。如果元素不在列表中,那么它将继续运行。大概,
get_next()
返回最后一个元素的None
,因此在循环遍历列表中的所有元素后,当前变为None
。下一次在循环中调用current.get_data()
,也就是说,这不起作用,因为current
是None
,None
没有get_data
成员,就像错误消息所说的那样
要解决这个问题,需要在到达数组末尾时停止循环。您可以通过将while修改为
while current is not None and not found:
self.head
或varaible是一个函数吗?当您到达列表的末尾时,current.get\u next()
返回None
,下次循环时,您将调用该函数上的get\u data()
(通过从空列表中删除一项,您将获得相同的行为)。当current为None时,您需要退出while循环
,并忘记found
。