剑指 Offer 06. 从尾到头打印链表(栈)

在这里插入图片描述

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

猜你喜欢

转载自blog.csdn.net/qq_43434328/article/details/115082770