剑指offfer 从尾到头打印链表

题目链接

1.for循环

class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode temp = head;
        int n = 0;
        while(temp!=null){
            temp = temp.next;
            n++;
        }
        int[] a = new int[n];
        //将链表中的值倒着存入数组
        for(int i = n-1;i>=0;i--){
            a[i] = head.val;
            head = head.next;
        }
        return a;
    }
}

2.递归

class Solution {
    ArrayList<Integer> list = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        //调用递归函数,将链表中的元素反向追加到list中
        digui(head);
        int[] a = new int[list.size()];
        for(int i = 0;i<list.size();i++){
            a[i] = list.get(i);
        }
        return a;
    }
    void digui(ListNode head){
        if(head==null) return;
        digui(head.next);
        //回溯时将每个节点的值添加到list中
        list.add(head.val);
    }
}

posted @ 2022-02-02 14:31  蹇爱黄  阅读(32)  评论(0)    收藏  举报