用两个栈实现队列---剑指Offer(Java版)

版权声明:转载请点赞,当然附上原文链接也很不错 https://blog.csdn.net/m0_37961948/article/details/88375229

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

 队列:先进先出(正序进入,正序弹出)

栈:先进后出(正序进入,逆序弹出)

两个栈:一个栈逆序弹出到另一个栈,则第二个栈弹出时变为正序.

Stack<Integer> head = new Stack<Integer>();
    Stack<Integer> last = new Stack<Integer>();

    public void push(int node) {
        last.add(node);
    }

    public int pop() {
        // 当正序弹出的栈中没有值的时候,从逆序栈中取出所有元素.
        if(head.size() == 0){
            while (last.size() != 0){
                head.add(last.pop());
            }
        }
        // if (head.size() == 0) throw Exception
        return head.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37961948/article/details/88375229