从尾到头打印链表

从尾到头打印链表

题目

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

栈按照先进后出的原则存储数据,可以利用栈

图解

从尾到头打印链表.gif

代码实现

class Solution {
    public int[] reversePrint(ListNode head) {
        //1. 先创建一个栈
        LinkedList<Integer> stack = new LinkedList<Integer>();
        //2. 遍历链表
        while(head != null){
            stack.addLast(head.val);
            head = head.next;
        }
        //3. 创建一个数组存放
        int[] num = new int[stack.size()];
        for( int i = 0; i < num.length; i++){
            num[i] = stack.removeLast();
        }
        return num;
    }
}
posted @ 2020-11-08 21:51  南煎丸子  阅读(45)  评论(0编辑  收藏  举报