[剑指offer][JAVA]面试题第[06]题[从尾到头打印链表][栈][递归]

239 篇文章 1 订阅
【问题描述】[简单]
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

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

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

【解答思路】
1. 常规思路
  • 遍历链表 得到链表个数
  • 新建数组 遍历链表复制val
    时间复杂度:O(N) 空间复杂度:O(N)
public int[] reversePrint(ListNode head) {
  int count = 0;
        ListNode temp = head;
        while (temp != null) {
            count++;
            temp = temp.next;
        }
        
        int[] res = new int[count];
        for (int i = count - 1; i > -1; i--) {
            res[i] = head.val;
            head = head.next;
        }

        return res;
    }
2. 栈

在这里插入图片描述
时间复杂度:O(N) 空间复杂度:O(1)

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;
    }
}


3. 递归

在这里插入图片描述
时间复杂度:O(N) 空间复杂度:O(1)

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);
    }
}


【总结】
1.数组是不能使用集合的反转方法的,可以自定义方法实现数组反转
public static int[] reserve( int[] arr ){
    int[] arr1 = new int[arr.length];
    for( int x=0;x<arr.length;x++ ){
        arr1[x] = arr[arr.length-x-1];
    }
    return arr1 ;
}
2.ArrayList使用函数反转

在这里插入图片描述

3.不建议使用stack

为什么用LinkedList不用Stack
基于 Vector 实现的栈 Stack底层是数组 扩容开销大
Java并不推荐使用java.util.stack来进行栈的操作,而是推荐使用一个双端队列deque
详情链接:https://www.cnblogs.com/cosmos-wong/p/11845934.html

转载链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值