232. Implement Queue using Stacks

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

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

相当于output专门用做输出,每对queue调用一次pop,就从output里面输出,output空的时候,就把input里面的逆序压入output,再从output输出。

评论

此博客中的热门博文

225 Implement Stack using Queues

20. Valid Parentheses