Open In App

Implement a stack using single queue

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
79 Likes
Like
Report

We are given a queue data structure, the task is to implement a stack using a single queue.

Also Read: Stack using two queues

The idea is to keep the newly inserted element always at the front of the queue, preserving the order of previous elements by appending the new element at the back and rotating the queue by size n so that the new item is at the front.

// Push an element x in the stack s
push(s, x)
1) Let size of q be s.
1) Enqueue x to q
2) One by one Dequeue s items from queue and enqueue them.

// pop an item from stack s
pop(s)
1) Dequeue an item from q

C++
#include<bits/stdc++.h>
using namespace std;

// User defined stack that uses a queue
class Stack
{
    queue<int>q;
public:
    void push(int val);
    void pop();
    int top();
    bool empty();
};

// Push operation
void Stack::push(int val)
{
    //  Get previous size of queue
    int s = q.size();

    // Push current element
    q.push(val);

    // Pop (or Dequeue) all previous
    // elements and put them after current
    // element
    for (int i=0; i<s; i++)
    {
        // this will add front element into
        // rear of queue
        q.push(q.front());

        // this will delete front element
        q.pop();
    }
}

// Removes the top element
void Stack::pop()
{
    if (q.empty())
        cout << "No elements\n";
    else
        q.pop();
}

// Returns top of stack
int  Stack::top()
{
    return (q.empty())? -1 : q.front();
}

// Returns true if Stack is empty else false
bool Stack::empty()
{
    return (q.empty());
}

// Driver code
int main()
{
    Stack s;
    s.push(10);
    s.push(20);
    cout << s.top() << endl;
    s.pop();
    s.push(30);
    s.pop();
    cout << s.top() << endl;
    return 0;
}
Java Python C# JavaScript

Output
20
10

Time complexity

For Push Operations: O(n) as we need to rotate the queue to bring the newly added element to the front. ( where n is the size of the queue )
For Pop Operations: O(1)

Auxiliary Space: O(n)


Article Tags :
Practice Tags :

Similar Reads