我是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函数有问题,因为它不能处理不在列表中的值,但是我现在很难理解如何让它工作。感谢任何帮助!在
这有点难搞清楚,因为你还没有发布真正的LinkedList,但是我假设你打了
current.get_next()
太多次了,你可能会到达列表的末尾。也许像这样的东西对你有魔力(更新):您使用
None
来表示列表中没有其他节点,也就是说,您位于列表的末尾,但是在搜索列表时,您永远不会对此进行测试,因此当您到达末尾时,您尝试调用None.get_data()
。解决方案:不要这样做。在重做循环的一个好方法可能是将
while
循环改为测试current
,并在找到项时使用break
退出循环。在你需要重做后面的一些逻辑来解释这个问题。您不需要单独的
found
标志;您只需检查current
。如果是None
,则到达列表末尾时没有找到要查找的项。否则,你找到了它,current
就是它。在相关问题 更多 >
编程相关推荐