Queue Reversal

Problem Statement:

Given a queue, you need to reverse it.

Solution

This problem can be solved in 2 different methods.

Method 1:

Using stack.

Pop the elements from queue and insert into stack.

Then pop the elements from stack and insert into queue.

Method 2:

Using recursion.

In recursion, we pop an element and store it in a temp variable.

Then we continue to pop the elements till the queue is empty.

Then when the queue is empty, we will insert that element into the queue.

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;
  
void display_queue(queue<int>& Queue)
{
    while (!Queue.empty()) 
    {
        cout << Queue.front() << " ";
        Queue.pop();
    }
}
  
void reverse_queue_using_stack(queue<int>& Queue)
{
    stack<int> Stack;
    while (!Queue.empty()) 
    {
        Stack.push(Queue.front());
        Queue.pop();
    }
    while (!Stack.empty()) 
    {
        Queue.push(Stack.top());
        Stack.pop();
    }
}

void reverse_queue_using_recursion(queue<int>& Queue)
{
    if (Queue.empty())
        return;
  
    int data = Queue.front();
    Queue.pop();
  
    reverse_queue_using_recursion(Queue);
  
    Queue.push(data);
}
  
int main()
{
    queue<int> Queue;
    Queue.push(10);
    Queue.push(20);
    Queue.push(30);
    Queue.push(40);
    Queue.push(50);
  
   cout<<"Reverse the queue using stack: ";
    reverse_queue_using_stack(Queue);
    display_queue(Queue);

    Queue.push(10);
    Queue.push(20);
    Queue.push(30);
    Queue.push(40);
    Queue.push(50);
  
   cout<<"\nReverse the queue using recursion: ";
    reverse_queue_using_recursion(Queue);
    display_queue(Queue);

}

Output:

Reverse the queue using stack: 50 40 30 20 10
Reverse the queue using recursion: 50 40 30 20 10

 

 

 

 

Write a Comment

Leave a Comment

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