【发布时间】: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