递归构造链表插入函数

construct insert function of linkedlist recursively

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,所以它可以像列表一样使用。但是我不知道我对这两个做错了什么。我无法获得我想要的功能。

问题是你的方法 return None(正如你仔细记录的那样!)所以特别是赋值

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

破坏列表结构。删除 self.rest = 部分(虽然无害,但上面的 self = ,为了清楚起见,如果没有别的!),这应该有所帮助。您可能还有其他问题(我相信插入索引可能意味着从 0 开始)但是这个问题会立即跳出,因为绝对是错误的。