0
点赞
收藏
分享

微信扫一扫

3.用数组逆序打印链表

weipeng2k 2022-05-04 阅读 88
java算法

其实我最先想到的是用栈,因为栈是“先进后出”

class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<Integer>();//定义栈
        while(head != null){
            stack.addLast(head.val);
            head = head.next;
        }
        int[] array = new int[stack.size()];
        for(int i = 0;i <array.length;i++){
            array[i] = stack.removeLast();
        }
        return array;
    }
}
举报

相关推荐

0 条评论