【发布时间】:2015-01-02 21:54:07
【问题描述】:
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
所以我想递归地构造插入方法。并且我已经改变了一些内置函数,如 getitem 和 len,所以它可以像 list 一样使用。但我不知道我对这两个做错了什么。我无法获得我想要的功能。
【问题讨论】:
-
这看起来有点像家庭作业……是吗?
-
不……我正在自学——我们这个学期还没有开始。
标签: python recursion linked-list