【问题标题】:Unexpected result in linked list reverse print using recursion使用递归的链表反向打印的意外结果
【发布时间】:2020-01-22 10:32:45
【问题描述】:

我使用递归以相反的顺序打印链表。我在玩代码并在递归调用上方添加了另一个打印语句,并希望它以原始顺序打印链接列表,但它只打印列表的第一个元素。我的链表有以下数据

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

链表被正确反转,但为什么第一个打印语句只工作?我希望它以原始顺序打印整个列表。

【问题讨论】:

    标签: python recursion linked-list


    【解决方案1】:

    您在递归中调用了错误的函数: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
    0
    

    【讨论】:

    • 非常感谢。我尝试了不同的函数,但忘记更改函数内部的名称。
    猜你喜欢
    • 2021-11-30
    • 2013-06-02
    • 1970-01-01
    • 2014-11-27
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多