【问题标题】:Return Sublist of Singly Linked List Recursively递归返回单链表的子表
【发布时间】:2020-11-15 15:13:48
【问题描述】:

我正在尝试递归返回单链表的子列表。

例如。 list = 3->4->5->无

sub(list, 1, 2) 应该返回 4->5

参数 1 - 起始索引

参数 2 - 子列表的长度

我有点麻烦,因为我的代码只返回子列表的最后一个元素,而不是整个子列表。

def sub(list, start, length) -> Node:
    if list is None:
        return None
    elif start <= 0:
        if length ==1:
            list.next = None
            return list
        else:
            return sub(list.next, start - 1, length - 1)
    else:

        return sub(list.next, start - 1, length)

【问题讨论】:

  • 您或许应该包含更多代码。 'yield' 和 'yield from' 在这里可能比 'return' 更好。对于许多操作,python 中的链接列表比内置列表类型慢得多,您需要的只是一个具有内置列表类型的切片。使用名为“list”的变量将屏蔽内置列表类型的构造函数——“list_”或“lst”会更好。
  • 顺便说一句,如果你使用'yield',你不需要你的可调用对象是递归的。

标签: python algorithm recursion


【解决方案1】:

您可以在您的sub 函数中使用一个参数,该参数在您遍历主结构时存储累积的子列表:

def sub(lst, s, e, c = 0, new_l = None):
   if c >= e:
      return new_l
   if lst is None:
      raise IndexError('index out of bounds')
   return sub(lst.next, s, e, c = c+1, new_l = None if c + 1 <= s else getattr(new_l, 'add_node', Lst)(lst.value))

Lst 实现:

class Lst:
   def __init__(self, val=None):
      self.value, self.next = val, None
   def add_node(self, val):
      if self.value is None:
         self.value = val
      elif self.next is None:
         self.next = Lst(val)
      else:
         self.next.add_node(val)
      return self
   def __repr__(self):
      return f'{self.value}{"" if self.next is None else " -> "+repr(self.next)}'


l = Lst()
for i in range(10):
   l.add_node(i)

print(sub(l, 0, 4))
print(sub(l, 2, 7))
print(sub(l, 5, 12))

输出:

0 -> 1 -> 2 -> 3
2 -> 3 -> 4 -> 5 -> 6
  File "<stdin>", line 6, in sub
  [Previous line repeated 7 more times]
File "<stdin>", line 5, in sub
IndexError: index out of bounds

【讨论】:

    猜你喜欢
    • 2020-09-09
    • 2014-01-18
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多