02.从尾到头打印链表

从尾到头打印链表

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

//输入
head = [1,3,2]
//输出
[2,3,1]
//限制:
0 <= 链表长度 <= 10000

递归法

代码的关键部分是recur递归函数

假设输入的链表存储着【1,3,2】这样的一组数据

第一次调用recur函数时(head值为1):head!=null继续走,

第二调用recur函数(head值为3),不过传入的参数是head.next,

接着第三次调用recur函数(head值为2),

当第四次调用recur函数时,head==null函数return,程序返回到第三次调用的recur函数,

这时tmp开始了第一次add,add的值为2,也就是链表指向的最后一个节点的值,

第三次调用的recur函数执行结束,程序回到第二次调用的recur函数,开始第二次tmp.add,

第二次调用的recur函数执行结束,程序回到第一次调用的recur函数,开始第三次tmp.add,这时添加的数据也就时链表的第一个元素

【时间复杂度】O(N):遍历链表,递归 N 次

【空间复杂度】O(N):系统递归需要使用O(N)的栈空间

class Solution {
    ArrayList<Integer> tmp = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int[] res = new int[tmp.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = tmp.get(i);
        return res;
    }
    void recur(ListNode head) {
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }
}

作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5d8831/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

辅助栈法

这个解法思路很简单,链表访问节点时是从前到后,逆序输出刚好满足了【先入后出栈】的特点,可以直接将链表中个节点值按照正常顺序压入【先入后出栈】中,正常的出栈就满足了逆序输出

class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<Integer>();
        while(head != null) {
            stack.addLast(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = stack.removeLast();
    return res;
    }
}

作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5d8831/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值