剑指offer06-从尾到头打印链表

原题(来源Leetcode)

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

示例1:

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

限制:

0 <= 链表长度 <= 10000

解法

思想

代码

class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        int size = 0;
        while(head!=null){
            stack.push(head.val);
            head = head.next;
            size++;
        }
        int[] ans = new int[size];
        for(int i = 0;i<size;i++){
            ans[i] = stack.pop();
        }
        return ans;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/%e5%89%91%e6%8c%87offer06-%e4%bb%8e%e5%b0%be%e5%88%b0%e5%a4%b4%e6%89%93%e5%8d%b0%e9%93%be%e8%a1%a8/

发表回复

登录后才能评论