问题描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
输入
head = [1,3,2]
返回值
[2,3,1]
解题思路
使用栈的特性FILO使输出顺序反转。
Java代码实现
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
while (head != null) {
stack.push(head);
head = head.next;
}
int[] res = new int[stack.size()];
for (int i = 0; i < res.length; ++i) {
res[i] = stack.pop().val;
}
return res;
}
} 
京公网安备 11010502036488号