剑指 Offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表

题目

链接

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

问题描述

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

示例

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

提示

0 <= 链表长度 <= 10000

思路

采用栈的先进后出性质,存放值即可,之后输出到数组中。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(n)

代码

Java

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }


    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.add(head.val);
            head = head.next;
        }
        int size = stack.size();
        int[] ans = new int[size];

        for (int i = 0; i < size; i++) {
            ans[i] = stack.pop();
        }
        return ans;
    }
posted @ 2020-02-24 19:49  cheng102e  阅读(66)  评论(0编辑  收藏  举报