December 23, 2019

232. Implement Queue using Stacks

232. Implement Queue using Stacks

Two Stacks. Stack 1 is the only stack to store new elements when adding a new element into the queue.
Stack 2 is the only stack to pop old element out of the queue. When stack2 is empty, we move all data from Stack1 to Stack2.

Push - O(1) per operation, Pop - Amortized O(1) per operation.

class MyQueue {
    
    private Deque<Integer> stack1;
    private Deque<Integer> stack2;

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