0

无效反向(节点头){如果(头==空)返回;

    reverse(head.next);
    System.out.print(head.data+" ");
}
4

2 回答 2

3

它从末尾打印链接列表的内容。

考虑这个简单的列表:1 -> 2 -> 3

现在让我们“分解”调用:

reverse(1) :
    reverse(2) :
        reverse(3) :
        print(3)
    print(2)
print(1)

神奇的发生是因为 println 在递归调用之后被调用!尝试把它放在前面会以正常顺序打印列表。

于 2020-05-26T15:21:23.100 回答
1

本质上,您正在反转链表的跟踪过程。

void reverse(Node head) {
        if(head==null) //if head points to nothing
             return;
        reverse(head.next); #if head points to something, move one position in reverse, because of the recursion, the function is called again before printing anything
        System.out.print(head.data+" "); #print the data stored in the nodes, reversed
}
于 2020-05-26T15:41:52.873 回答