конструкция вставки функция LinkedList рекурсивно
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, поэтому его можно использовать как список. Но я не знаю, что я сделал не так с этими двумя. Я не могу получить желаемую функцию.
Это выглядит подозрительно, как домашнее задание ... Не так ли? – Joel
Нет ... Я изучаю это сам - мы еще не начали этот семестр. – jack