面试题 03.04. 化栈为队

面试题 03.04. 化栈为队 #

题目 #

  • 实现一个 MyQueue 类,该类用两个栈实现一个队列。

思路 #

代码 #

class MyQueue {
    Stack<Integer> inStack, outStack;

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

/**
 * 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();
 */