[英]Return Sublist of Singly Linked List Recursively
I am trying to return the sublist of a singly linked list recursively.我试图递归地返回单向链表的子列表。
Ex.前任。 list = 3->4->5->None列表 = 3->4->5->无
sub(list, 1, 2) should return 4->5 sub(list, 1, 2) 应该返回 4->5
param 1 - start index参数 1 - 起始索引
param 2 - length of sublist参数 2 - 子列表的长度
I am having a little trouble as my code only returns the last element of the sublist and not the whole sublist.我遇到了一点麻烦,因为我的代码只返回子列表的最后一个元素而不是整个子列表。
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)
You can use a parameter in your sub
function that stores the accumulated sub list as you traverse the main structure:您可以在sub
function 中使用一个参数来存储遍历主结构时累积的子列表:
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
implemenation: 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))
Output: Output:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.