《剑指Offer》6. 从尾到头打印链表

题目链接

牛客网

题目描述

从尾到头反过来打印出每个结点的值。

解题思路

利用栈后进先出的特性, O(N),O(N)

class Solution {
   
    public int[] reversePrint(ListNode head) {
   
        if (head==null) return new int[0];
        Deque<Integer> stack = new LinkedList<>();
        int len = 0;
        while (head!=null) {
   
            stack.push(head.val);
            head = head.next;
            len++;
        }
        int[] res = new int[len];
        for (int i=0; i<len; i++)
            res[i] = stack.pop();
        return res;
    }
}
全部评论

相关推荐

WhiteAlbum...:学院本2中大厂垂直实习➕acm比赛 秋招0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务