Python 使用递归进行链表反向打印时出现意外结果
我使用递归以相反的顺序打印链表。我在玩代码,并在递归调用上方添加了另一个print语句,希望它按原始顺序打印链表,但它只打印列表的第一个元素。我的链接列表包含以下数据Python 使用递归进行链表反向打印时出现意外结果,python,recursion,linked-list,Python,Recursion,Linked List,我使用递归以相反的顺序打印链表。我在玩代码,并在递归调用上方添加了另一个print语句,希望它按原始顺序打印链表,但它只打印列表的第一个元素。我的链接列表包含以下数据 0 --> 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 链表类- class node_obj: def __init__(self, d): self.data = d self.next = None 我的递归函数- def recur
0 --> 1 --> 2 --> 3 --> 4 --> 5 --> 6 -->
链表类-
class node_obj:
def __init__(self, d):
self.data = d
self.next = None
我的递归函数-
def recursive_revers1(head):
if head != None:
print('--------', head.data)
recursive_rev(head.next)
print(head.data)
recursive_revers1(head)
输出:
-------- 0
6
5
4
3
2
1
0
链表被正确地颠倒了,但是为什么第一个print语句只对其中的一个起作用?我希望它按原始顺序打印整个列表。您在递归中调用了错误的函数:
recursive\u rev
(可能是代码的早期版本),但您的递归函数现在称为recursive\u revers1
。这对我很有用:
def recursive_revers1(head):
if head: # recommended way to ask if something is not None
print('--------', head.data)
recursive_revers1(head.next) # here was the mistake
print(head.data)
recursive_revers1(head)
现在,在控制台中,我们可以看到:
-------- 0
-------- 1
-------- 2
-------- 3
-------- 4
-------- 5
-------- 6
6
5
4
3
2
1
0
谢谢。我尝试了不同的函数,但忘记更改函数中的名称。