剑指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 @   蹇爱黄  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示