题目来源

232. 用栈实现队列

思路

方法一 双栈

创建两个栈,一个为入栈,一个为出栈。

队列是按照先进先出的原则执行的。

当队列执行入队操作,我们将入队的元素添加到入栈中。

当队列执行出队操作,我们首先要把入栈中的元素根据栈的先进后出原则,添加到出栈中,然后再将出栈中的栈顶元素弹出。

注意:在每次要执行出队操作前,都要先判断出栈的栈内元素是否为空,如果不为空,则直接将栈顶元素弹出即可,如果为空,则将入栈中的元素添加到出栈中。

class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;
    /** Initialize your data structure here. */
    public MyQueue() {
        in=new Stack<Integer>();
        out=new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(out.isEmpty()){
            while(!in.isEmpty()) out.push(in.pop());
        }
        return out.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(out.isEmpty()){
            while(!in.isEmpty()) out.push(in.pop());
        }
        return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty()&&out.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

参考来源

  1. 官方题解