美文网首页
232. 用栈实现队列

232. 用栈实现队列

作者: justonemoretry | 来源:发表于2021-08-09 22:47 被阅读0次
image.png

解法

class MyQueue {
    // 输入栈
    private Stack<Integer> inStack;
    // 输出栈
    private Stack<Integer> outStack;

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

相关文章

网友评论

      本文标题:232. 用栈实现队列

      本文链接:https://www.haomeiwen.com/subject/mdvtbltx.html