3.用数组逆序打印链表

weipeng2k

关注

阅读 89

2022-05-04

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

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)

0 0 举报