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,所以它可以像列表一样使用。但我不知道这两个我做错了什么。我无法得到我想要的功能。
答案 0 :(得分:0)
问题是你的方法返回None
(当你仔细记录时!)所以特别是作业
self.rest = self.rest.insert(index-1,item)
破坏列表结构。删除self.rest =
部分(虽然无害,但是上面是self =
,为了清楚起见,如果没有别的!)这应该有所帮助。您可能还有其他问题(我相信插入的索引可能意味着从0
开始),但是这个问题很快就会跳出来,因为绝对错误。