Implement Queue as stack.

Implement the following operations of a queue using stack(s).

  1. push(x) -- Push element x to the back of queue.
  2. pop() -- Removes the element from in front of queue.
  3. peek() -- Get the front element.
  4. empty() -- Return whether the queue is empty.

To understand more about Stack, refer the link What is Stack?


It's a fun problem to solve, and can be done by maintaining the 2 stacks. Since stack stores the newest element on top of the stack, while doing pop() on Queue, it should be last element to pop out. For this we can maintain another stack and fill it by removing element from the first stack. Note now the order of removing element from the other stack will be same as Queue

class MyQueue {

    Stack<Integer> input = new Stack();
    Stack<Integer> output = new Stack();
    
    public void push(int x) {
        input.push(x);
    }

    public void pop() {
        peek();
        output.pop();
    }

    public int peek() {
        if (output.empty())
            while (!input.empty())
                output.push(input.pop());
        return output.peek();
    }

    public boolean empty() {
        return input.empty() && output.empty();
    }
}