欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2023/12/10 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [剑指offer][JAVA]面试题第[06]题[从尾到头打印链表][栈][递归] 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

【问题描述】[简单]

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。示例 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/

总结

以上是生活随笔为你收集整理的[剑指offer][JAVA]面试题第[06]题[从尾到头打印链表][栈][递归]的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。