剑指 Offer 06. 从尾到头打印链表
描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
链接
剑指 Offer 06. 从尾到头打印链表 - 力扣(LeetCode) (leetcode-cn.com)
解法:用栈
1 class Solution { 2 public int[] reversePrint(ListNode head) { 3 LinkedList<Integer> stack = new LinkedList<Integer>(); 4 while(head != null) { 5 stack.push(head.val); 6 head = head.next; 7 } 8 int[] res = new int[stack.size()]; 9 for(int i = 0; i < res.length; i++) 10 res[i] = stack.pop(); 11 return res; 12 } 13 }