【问题标题】:construct insert function of linkedlist recursively递归构造链表的插入函数
【发布时间】: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


【解决方案1】:

问题是你的方法返回None(你仔细记录了!)所以特别是分配

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

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

【讨论】:

  • 谢谢。我改变了我的代码,现在它终于可以工作了。这是主要原因。
猜你喜欢
  • 2017-06-12
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
相关资源
最近更新 更多