Implement a stack using single queue

Implement a stack using single queue

We are given queue data structure, the task is to implement stack using only given queue data structure.
We have discussed a solution that uses two queues. In this article, a new solution is discussed that uses only one queue. This solution assumes that we can find size of queue at any point. The idea is to keep newly inserted element always at front, keeping order of previous elements same. Below are complete steps.

// x is the element to be pushed and s is stack
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.
// Removes an item from stack
  1) Dequeue an item from q

Below is C++ implementation of the idea.

// C++ program to implement a stack using
// single queue
using namespace std;

// User defined stack that uses a queue
class Stack
    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

    // 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

        // this will delete front element

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

// 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;
    cout << << endl;
    cout << << endl;
    return 0;

Output :


This article is contributed byManu Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s