面試題06.從頭到尾打印鏈表
題目描述
輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
示例 1:
輸入:head = [1,3,2]
輸出:[2,3,1]
限制:
0 <= 鏈表長度 <= 10000
題解
從尾到頭反過來返回每個節點的值,很容易想到藉助棧來完成,先按順序存入棧,之後出棧入數組即得結果,代碼如下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
//鏈表節點值入棧
while(head!=null){
stack.push(head.val);
head = head.next;
}
//出棧入數組
int[] res = new int[stack.size()];
for(int x=0;x<res.length;x++){
res[x] = stack.pop();
}
return res;
}
}