Implement Stack using Queues

Problem Statement:

You need to create stack data structure using only queue data structure.

Solution

As we know that for stack insertion and deletion happen on the same end. i.e last in first out.

But in queue, insertion and deletion will happen on different end. First in first out.

Steps to solve this problem:

While pushing an element into the queue.

Then we rotate the queue, in such a way that the newly pushed element is at the end of the queue.

So when you pop the element, it will be the new element.

Example:
push 1 -> [1]       and no rotate
push 2 -> [2,1]     and rotate 1 time : -> [1,2]
push 3 -> [2,1,3]   and rotate 2 times: -> [1,3,2] -> [3,2,1]
push 4 -> [3,2,1,4] and rotate 3 times: -> [2,1,4,3] -> [1,4,3,2] -> [4,3,2,1]

 

Solution in C++

#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <queue>
#include <vector>
#include <stack> 

using namespace std;
  
class Stack 
{
public:
   queue<int> que;

   void push(int x) 
   {
      que.push(x);
      for(int i=0;i<que.size()-1;++i)
      {
         que.push(que.front());
         que.pop();
      }
   }

   void pop() {
      que.pop();
   }

   int top() {
      return que.front();
   }

   bool empty() {
      return que.empty();
   }
};
 
int main() 
{ 
    Stack s; 
    s.push(1); 
    s.push(2); 
    s.push(3); 
  
    cout <<"Top element = "<< s.top() << endl; 
    s.pop(); 
    cout <<"Top element = "<<  s.top() << endl; 
    s.pop(); 
    cout <<"Top element = "<<  s.top() << endl; 
  

    return 0; 
} 

Output:

Top element = 3
Top element = 2
Top element = 1

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *