【问题标题】:error implement delete function for linked list using Python错误使用Python实现链表的删除功能
【发布时间】:2015-02-03 23:16:54
【问题描述】:

您好,我正在尝试通过执行第一个任务来学习 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。谁能帮我?谢谢!

【问题讨论】:

  • self.head 或者一个变量是一个函数?
  • 你正在到达列表的末尾,current.get_next() 正在返回 None 并且下次循环调用 get_data() 时(通过从空列表)。 current is None 时需要退出 while 循环,忘记 found

标签: python linked-list


【解决方案1】:

只有当你真正找到元素时,你的循环才会停止。如果该元素不在列表中,则它会继续运行。据推测,get_next() 为最后一个元素返回None,因此在遍历列表中的所有元素后current 变为None。下一次循环调用current.get_data(),即这不起作用,因为currentNoneNone 没有get_data 成员,就像错误消息所说的那样。

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

while current is not None and not found:

【讨论】:

    【解决方案2】:

    当您处于循环中时,在尝试访问其数据之前,您需要确保 current 不是 None。我能想到的最简单的处理方法是简单地返回None

    while not found:
        if current is None:
            return
        # rest of loop
    

    【讨论】:

      猜你喜欢
      • 2017-10-06
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2018-07-31
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多