每日一题 leetcode232-用栈实现队列

232用栈实现队列

https://leetcode-cn.com/problems/implement-queue-using-stacks/

代码:

class MyQueue {
    private Stack inStack;
    private Stack 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() {
        if(!outStack.isEmpty()){
            return outStack.peek();
        }
        while(!inStack.isEmpty()){
            outStack.push(inStack.pop());
        }
        return outStack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return outStack.isEmpty()&&inStack.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();
 */

你可能感兴趣的:(每日一题 leetcode232-用栈实现队列)