Implement Stack using Queues

Last Updated : 25 Jul, 2026

Implement a stack using queue(s). Only queue operations are allowed to perform stack operations.

Dequeue-Operation-in-Queue-2

The stack should support the following operations:

  • push(x): Insert element x onto the top of the stack.
  • pop(): Remove the element from the top of the stack. If the stack is empty, do nothing.
  • top(): Return the element at the top of the stack. If the stack is empty, return -1.
  • size(): Return the number of elements in the stack.
Try It Yourself
redirect icon

Using Two Queue - Push in O(n) and Pop() in O(1)

We will be using two queues (q1 and q2) to implement the stack operations.

The main idea is to always keep the newly inserted element at the front of q1, so that both pop() and top() can directly access it. Queue q2 acts as a helper to rearrange elements during push().

Push Operation

  • Enqueue the new element x into q2.
  • Move all elements from q1 into q2, one by one.
  • Swap the names of q1 and q2. After the swap, q1 contains the updated stack order with the newest element at the front.

Pop Operation

  • If q1 is empty, the stack is empty (underflow condition).
  • Otherwise, dequeue from the front of q1, which represents the top of the stack.

Find the Top Element

  • If q1 is empty, return -1.
  • Otherwise, return the front element of q1, since it represents the current top of the stack.

Find the Size of the Stack

  • Simply return the number of elements in q1, which tracks the current stack size.
C++
#include <iostream>
#include <queue>
using namespace std;

class myStack {
    
    queue<int> q1, q2;

public:
    void push(int x) {
        
        // Push x first in empty q2
        q2.push(x);

        // Push all the remaining
        // elements in q1 to q2.
        while (!q1.empty()) {
            q2.push(q1.front());
            q1.pop();
        }

        // swap the names of two queues
        swap(q1, q2);
    }

    void pop()
    {
        // if no elements are there in q1
        if (q1.empty())
            return;
        q1.pop();
    }

    int top()
    {
        if (q1.empty())
            return -1;
        return q1.front();
    }

    int size() { return q1.size(); }
};

int main() {
    myStack st;
    st.push(1);
    st.push(2);
    st.push(3);

    cout << st.top() << endl;
    st.pop();
    cout << st.top() << endl;
    st.pop();
    cout << st.top() <<