題目描述
輸入一個(gè)鏈表的頭結(jié)點(diǎn)哄辣,從尾到頭打印出每個(gè)節(jié)點(diǎn)的值蹄衷。
解題思路一:
- 遍歷鏈表赔蒲,將遍歷到的節(jié)點(diǎn)以此放入棧中泌神。
- 從棧頂逐一輸出節(jié)點(diǎn),此時(shí)輸出的節(jié)點(diǎn)順序已經(jīng)反過來了舞虱。
解題思路二:
- 使用遞歸欢际。
代碼
// 使用棧
void printListReverse(ListNode root){
if (root == null) {
return;
}
Stack<ListNode> stack = new Stack<>();
while (root != null) {
stack.push(root);
root = root.next;
}
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
// 遞歸的方式
void printListReverse_v2(ListNode root){
if (root == null) {
return;
}
printListReverse_v2(root.next);
System.out.println(root);
}