我使用递归以逆序打印链表。我修改了一下代码,并在递归调用的上面添加了另一个print语句,希望它能按原始顺序打印链表,但它只打印链表的第一个元素。我的链表包含以下数据
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语句只有1个呢?我希望它能按原来的顺序打印整个列表。
发布于 2019-09-22 05:12:43
您在递归中调用了错误的函数:recursive_rev (可能是代码的早期版本),但是您的递归函数现在称为recursive_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
0https://stackoverflow.com/questions/58044070
复制相似问题