Implement Queue Using Stacks

Companies:
  • Adobe Interview Questions
  • Apple Interview Questions
  • Microsoft Interview Questions
  • Oracle Interview Questions

Implement the following operations of a queue using stacks.

  • push(x) — Push element x to the back of queue.
  • pop() — Removes the element from in front of queue.
  • peek() — Get the front element.
  • empty() — Return whether the queue is empty.

Example:

MyQueue queue = new MyQueue();

queue.push(3);

queue.push(4);

queue.peek(); // returns 3

queue.pop(); // returns 3

queue.empty(); // returns false

Notes:

  • You must use only standard operations of a stack — which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Solution:

Queue is FIFO (First in first out) and Stack is LIFO (Last In First Out). To convert stack into queue, we need two stacks to store and retrieve elements. We will push all the elements in one stack but at the time when we need front element in queue we will simply reverse the elements by remove elements one by one from one stack to the other. This process will give the correct output as the elements are then arranged in the form of a queue.

Implementation:

Java:

 class MyQueue {
    Stack<Integer> s1, s2;
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

    public void push(int x) {
        while(!s2.isEmpty()){
            s1.push(s2.pop());
        }
        s1.push(x);
        while(!s1.isEmpty()){
            s2.push(s1.pop());
        }
    }

    public int pop() {
        return s2.pop();
    }

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

    public boolean empty() {
        return s2.size() == 0;
    }
}

Complexity Analysis:

  • Time Complexity: O(n)

  • Space Complexity: O(1)

Scroll to Top