Reversing a Queue

Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue.

1. enqueue(x) : Add an item x to rear of queue.
2. dequeue() : Remove an item from front of queue.
3. empty() : Checks if a queue is empty or not.

Examples:

```Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output :Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

Input :[1, 2, 3, 4, 5]
Output :[5, 4, 3, 2, 1]
```

C++

```// CPP program to reverse a Queue
#include <bits/stdc++.h>
using namespace std;

// Utility function to print the queue
void Print(queue<int>& Queue)
{
while (!Queue.empty()) {
cout << Queue.front() << " ";
Queue.pop();
}
}

// Function to reverse the queue
void reverseQueue(queue<int>& Queue)
{
stack<int> Stack;
while (!Queue.empty()) {
Stack.push(Queue.front());
Queue.pop();
}
while (!Stack.empty()) {
Queue.push(Stack.top());
Stack.pop();
}
}

// Driver code
int main()
{
queue<int> Queue;
Queue.push(10);
Queue.push(20);
Queue.push(30);
Queue.push(40);
Queue.push(50);
Queue.push(60);
Queue.push(70);
Queue.push(80);
Queue.push(90);
Queue.push(100);

reverseQueue(Queue);
Print(Queue);
}
```

Java

```// Java program to reverse a Queue
import java.util.Queue;
import java.util.Stack;

// Java program to reverse a queue
public class Queue_reverse {

static Queue<Integer> queue;

// Utility function to print the queue
static void Print()
{
while (!queue.isEmpty()) {
System.out.print( queue.peek() + ", ");
queue.remove();
}
}

// Function to reverse the queue
static void reversequeue()
{
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
queue.remove();
}
while (!stack.isEmpty()) {
stack.pop();
}
}

// Driver code
public static void main(String args[])
{

reversequeue();
Print();
}
}
//This code is contributed by Sumit Ghosh
```

Output

```100, 90, 80, 70, 60, 50, 40, 30, 20, 10
```

This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.5 Average Difficulty : 1.5/5.0
Based on 12 vote(s)