232.Implement Queue using Stacks

Solution 1:

The overall amortized cost for each operation is O(1).

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

class MyQueue {
    Stack<Integer> inputStack;
    Stack<Integer> outputStack;
    /** Initialize your data structure here. */
    public MyQueue() {
        inputStack = new Stack();
        outputStack = new Stack();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        inputStack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        fillOutputStackIfEmpty();
        return outputStack.pop();
    }

    /** Get the front element. */
    public int peek() {
        fillOutputStackIfEmpty();
        return outputStack.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return inputStack.empty() && outputStack.empty();
    }

    public void fillOutputStackIfEmpty(){
        if(outputStack.empty()){
            while(!inputStack.empty()){
                outputStack.push(inputStack.pop());
            }
        }
    }
}

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

results matching ""

    No results matching ""