我举一个简单的例子:
def find2_rec(head, o):
'''(LLNode, obj) -> LLNode
'''
if head == None:
result = (None, None)
elif head.data == o:
result = (head, None)
else:
(at_node, before_node) = find2_rec(head.next, o)
if head.next == at_node != None:
before_node = head
result = (at_node, before_node)
return result
考虑给你LLNode,它只是数据和下一个。此函数只返回对象及其前一个节点的节点,例如
的链接列表a = [1] -> [2] -> [3] -> [4] -> [5]
find2_rec(a,3) - >
([3] -> [4] -> [5], [2] -> [3] -> [4] -> [5])
是输出。我的问题是如何追踪这个?
我喜欢正常的递归,我喜欢这样写出来:
(列表示例的基本递归和)
rsum([1,2,3])
rsum([2,3])
rsum([3])
return 3
return 5 # 3 + 2
return 6 # 1 + 5
现在最适合LL的做法是什么?
我正在寻找的例子:
a = [1] -> [2] -> [3] -> [4] -> [5]
让我再次对find2_rec(a,3)说,我会将其描述为
[1] -> [2] -> [3] -> [4] -> [5]
[2] -> [3] -> [4] -> [5]
[3] -> [4] -> [5]
return [3] -> [4] -> [5], None
return ([3] -> [4] -> [5], [2] -> [3] -> [4] -> [5])
return ([3] -> [4] -> [5], [2] -> [3] -> [4] -> [5])
对于这么小的东西来说,写得太多了。还有更好的方法吗?