python - 使用Python实现链表删除功能时出错

标签 python linked-list

嗨,我正在尝试通过完成第一个作业来学习 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() ,即不起作用,因为 currentNoneNone没有get_data成员,就像错误消息所说的那样。

要解决这个问题,您需要在到达数组末尾时停止循环。您可以通过将 while 修改为

来做到这一点
while current is not None and not found:

关于python - 使用Python实现链表删除功能时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28310627/

相关文章:

python - BeautifulSoup:如何解析表中未标识的 TD 列表

Python 与 R 的 fromJSON()、unlist()、attr() 等价的函数?

c - 链接列表在第一次迭代后不打印值

c++ - 将 shared_ptr 用于 linked_list 在析构函数中给出 stackoverflow

c - 链表 - 段错误

循环链表进入无限循环

python - 金字塔和统计模型 fit() 和 ARIMA() 之间的区别?

python - numpy knn 与向量化嵌套矩阵

c - 如何在C中搜索图结构中的特定节点?

python - elif 中的语法错误阻止进一步执行