Python链接列表AttributeError:“NoneType”对象没有具有delete函数的“get_data”属性

2024-09-25 08:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,一直在尝试学习简单的数据结构。我已经能够为一个链表拼凑一些函数,但我的删除功能一直有问题。下面列出了所讨论的函数和测试用例: 类节点: definit(自身,初始数据): 自我数据=初始数据 自我。下一个=无

def get_data(self):
    return self.data

def get_next(self):
    return self.next

def set_data(self, new_data):
    self.data = new_data

def set_next(self, new_next):
    self.next = new_next

类链接列表: definit(自身): 自身.头部=无

^{pr2}$

我收到错误信息

"AttributeError: 'NoneType' object has no attribute 'get_data' with delete Function"

我相信delete函数有问题,因为它不能处理不在列表中的值,但是我现在很难理解如何让它工作。感谢任何帮助!在


Tags: 数据函数self数据结构列表newdataget
2条回答

这有点难搞清楚,因为你还没有发布真正的LinkedList,但是我假设你打了current.get_next()太多次了,你可能会到达列表的末尾。也许像这样的东西对你有魔力(更新):

def delete(self, item):     
    current = self.head # we don't need the previous variable
    previous = None
    found = False
    while current is not None and not found:
        if current.get_data() == item:
            found = True
        else:
            previous = current
            current = current.get_next()
    # at this point we should have either reached to end of the list
    # and current is None
    # or we have found the node we were looking for
    if found and previous is not None:
        # delete it
        previous.set_next(current.get_next())
    elif found and previous is None:
        # removing head element
        self.head = None
    else:
        # nothing found
        print("Do whatever you want here")

您使用None来表示列表中没有其他节点,也就是说,您位于列表的末尾,但是在搜索列表时,您永远不会对此进行测试,因此当您到达末尾时,您尝试调用None.get_data()。解决方案:不要这样做。在

重做循环的一个好方法可能是将while循环改为测试current,并在找到项时使用break退出循环。在

while current is not None:
    if current.get_data() == item:
        break
    else:
        previous = current
        current = current.get_next()

你需要重做后面的一些逻辑来解释这个问题。您不需要单独的found标志;您只需检查current。如果是None,则到达列表末尾时没有找到要查找的项。否则,你找到了它,current就是它。在

相关问题 更多 >