题目:

题解:
1、方法一:使用辅助栈实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public class Solution {
LinkedList<Integer> stack = null;
public int[] reversePrint(ListNode head) { stack = new LinkedList<Integer>(); while (!(head == null)){ stack.push(head.val); head = head.next; } int[] a = new int[stack.size()]; for (int i = 0; i < a.length; i++) { a[i] = stack.pop(); } return a; } }
|
方法二:使用递归实现(从后往前将链表中的数据放入list里)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution2 {
ArrayList<Integer> tmp = new ArrayList<>();
public int[] reversePrint(ListNode head) { recur(head); int[] a = new int[tmp.size()]; for (int i = 0; i < a.length; i++) { a[i] = tmp.get(i); } return a; }
void recur(ListNode head) { if (head == null) return; recur(head.next); tmp.add(head.val); } }
|