【剑指Offer】06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:
0 <= 链表长度 <= 10000

方法:递归

代码:

class Solution {
    ArrayList<Integer> arr = new ArrayList<>();
    public int[] reversePrint(ListNode head) {
        
        helper(head);
        int[] ans = new int[arr.size()];
        for(int i = 0; i < arr.size(); i++){
            ans[i] = arr.get(i);
        }
        return ans;
    }
    public void helper(ListNode head){
        if(head == null) return;
        helper(head.next);
        arr.add(head.val);
    }
}
posted @ 2020-05-13 22:47  Whisperbb  阅读(121)  评论(0编辑  收藏  举报