地址:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
实例1:
输入:head = [1,3,2]
输出:[2,3,1]
思路:栈
答案:
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<>();
ListNode temp = head;
while (temp != null) {
stack.push(temp.val);
temp = temp.next;
}
//size必须遍历前保存,否则遍历过程中会改变
int size = stack.size();
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = stack.pop();
}
return res;
}
}