void reverse(Node head( { if(head==null( 返回;
reverse(head.next);
System.out.print(head.data+" ");
}
它从末尾打印链表的内容。
考虑这个简单的列表: 1 -> 2 -> 3
现在让我们"分解"调用:
reverse(1) :
reverse(2) :
reverse(3) :
print(3)
print(2)
print(1)
神奇的发生是因为println是在递归调用之后调用的!尝试将其放在之前将按正常顺序打印列表。
从本质上讲,您正在逆转链表的跟踪过程。
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
}