递归构造linkedlist的插入函数

2024-09-30 22:27:48 发布

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

def insert(self, index, item): """ (LinkedListRec, int, object) -> NoneType Insert item at position index in this list. Raise an IndexError if index > len(self). But note that it is possible to insert an item at the *end* of a list (when index == len(self)). """ # Hint: take a look at remove and think about # what the base cases and recursive steps are. if index > len(self): raise IndexError if index == 1: self = self.insert_first(item) elif index > 1: self.rest = self.rest.insert(index-1,item) def insert_first(self, item): """ (LinkedListRec, object) -> NoneType Insert item at the front of the list. Note that this should work even if the list is empty! """ if self.is_empty(): print("been") self.first = item self.rest = LinkedListRec([]) else: temp = LinkedListRec([]) temp.first = self.first temp.rest = self.rest self.first = item self.rest = temp

所以我想递归地构造insert方法。我修改了一些内置函数,比如getitem和len,所以它可以像list一样使用。但我不知道我对这两个人做了什么错事。我得不到我想要的功能。在


Tags: theselfrestindexlenifisdef
1条回答
网友
1楼 · 发布于 2024-09-30 22:27:48

问题是您的方法返回None(仔细记录!)特别是任务

self.rest = self.rest.insert(index-1,item)

破坏列表结构。去掉self.rest =部分(尽管没有什么大碍,上面的self =也是为了清楚起见!)这应该有帮助。您可能还有其他问题(我相信插入的索引可能是从0开始的),但是这个问题很快就被认为是错误的。在

相关问题 更多 >