剑指 Offer 06. 从尾到头打印链表
题目来源:剑指 Offer 06.
题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
1 2
| 输入:head = [1,3,2] 输出:[2,3,1]
|
限制:
0 <= 链表长度 <= 10000
问题分析
示例代码
栈
1 2 3 4 5 6 7 8 9 10 11 12 13
| public int[] reversePrint(ListNode head) { Stack<Integer> stack = new Stack<>(); ListNode pNode = head; while(pNode !=null){ stack.push(pNode.val); pNode = pNode.next; } int[]ans = new int[stack.size()]; for(int i =0;i<ans.length;i++) ans[i]=stack.pop(); return ans; }
|
执行结果:
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| List<Integer> list= new ArrayList<>(); public int[] reversePrint(ListNode head) { ListNode pNode = head; reverseRecursion(pNode); int[]ans = new int[list.size()]; for(int i =0;i<ans.length;i++) ans[i]=list.get(i); return ans; } private void reverseRecursion(ListNode pNode){ if(pNode == null) return ; reverseRecursion(pNode.next); list.add(pNode.val); return ; }
|
执行结果: