题目地址(06. 从尾到头打印链表)

https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

题目描述

  1. 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
  2. 示例 1
  3. 输入:head = [1,3,2]
  4. 输出:[2,3,1]
  5. 限制:
  6. 0 <= 链表长度 <= 10000

前置知识


公司

  • 暂无

思路

借助栈

关键点


代码

  • 语言支持:Java

Java Code:

  1. class Solution {
  2. public int[] reversePrint(ListNode head) {
  3. Stack<Integer> stack = new Stack<>();
  4. while (head != null) {
  5. stack.push(head.val);
  6. head = head.next;
  7. }
  8. int[] ints = new int[stack.size()];
  9. for (int i = 0; i < ints.length; i++) {
  10. ints[i] = stack.pop();
  11. }
  12. return ints;
  13. }
  14. }

复杂度分析

令 n 为数组长度。

  • 时间复杂度:剑指 Offer 06. 从尾到头打印链表 - 图1#card=math&code=O%28n%29&id=G1fcs)
  • 空间复杂度:剑指 Offer 06. 从尾到头打印链表 - 图2#card=math&code=O%28n%29&id=cvmLU)