[leetcode] 232. Implement Queue Using Stacks

思路:使用两个栈
stackIn 负责 队列的 入队
stackOut 负责 队列的 出队

每次 q.peek() 或者 q.pop() 的时候都要从 stackOut 中取元素,此时需要看下该栈是否为空,如果为空则把 stackIn 的元素全部加入 stackOut 中来

class MyQueue {
    private Stack<Integer> stackIn;
    private Stack<Integer> stackOut;

    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();     
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        dumpStackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpStackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return (stackIn.isEmpty() && stackOut.isEmpty());
    }

    private void dumpStackIn() {
        if (!stackOut.isEmpty()) return;
        while (!stackIn.isEmpty()) {
            int t = stackIn.pop();
            stackOut.push(t);
        }
    }
}

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

你可能感兴趣的:(Algorithm,leetcode,算法,java)