# Reversing a Queue

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

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

The task is to reverse the queue.

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]

## Reversing a Queue using stack:

For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such a data structure that can serve the purpose. According to the approach, the data structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue.

Follow the below steps to implement the idea:

• Pop the elements from the queue and insert into the stack now topmost element of the stack is the last element of the queue.
• Pop the elements of the stack to insert back into the queue the last element is the first one to be inserted into the queue.

Below is the implementation of above approach:

## C++

 `// CPP program to reverse a Queue` `#include ` `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.LinkedList;` `import` `java.util.Queue;` `import` `java.util.Stack;`   `// Java program to reverse a queue` `public` `class` `Queue_reverse {`   `    ``static` `Queue 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 stack = ``new` `Stack<>();` `        ``while` `(!queue.isEmpty()) {` `            ``stack.add(queue.peek());` `            ``queue.remove();` `        ``}` `        ``while` `(!stack.isEmpty()) {` `            ``queue.add(stack.peek());` `            ``stack.pop();` `        ``}` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``queue = ``new` `LinkedList();` `        ``queue.add(``10``);` `        ``queue.add(``20``);` `        ``queue.add(``30``);` `        ``queue.add(``40``);` `        ``queue.add(``50``);` `        ``queue.add(``60``);` `        ``queue.add(``70``);` `        ``queue.add(``80``);` `        ``queue.add(``90``);` `        ``queue.add(``100``);`   `        ``reversequeue();` `        ``Print();` `    ``}` `}` `// This code is contributed by Sumit Ghosh`

## Python3

 `# Python3 program to reverse a queue` `from` `collections ``import` `deque`   `# Function to reverse the queue`     `def` `reversequeue(queue):` `    ``Stack ``=` `[]`   `    ``while` `(queue):` `        ``Stack.append(queue[``0``])` `        ``queue.popleft()`   `    ``while` `(``len``(Stack) !``=` `0``):` `        ``queue.append(Stack[``-``1``])` `        ``Stack.pop()`     `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``queue ``=` `deque([``10``, ``20``, ``30``, ``40``, ``50``, ``60``, ``70``, ``80``, ``90``, ``100``])`   `    ``reversequeue(queue)` `    ``print``(queue)`   `# This code is contributed by PranchalK`

## C#

 `// c# program to reverse a Queue` `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG {`   `    ``public` `static` `LinkedList<``int``> queue;`   `    ``// Utility function to print the queue` `    ``public` `static` `void` `Print()` `    ``{` `        ``while` `(queue.Count > 0) {` `            ``Console.Write(queue.First.Value + ``", "``);` `            ``queue.RemoveFirst();` `        ``}` `    ``}`   `    ``// Function to reverse the queue` `    ``public` `static` `void` `reversequeue()` `    ``{` `        ``Stack<``int``> stack = ``new` `Stack<``int``>();` `        ``while` `(queue.Count > 0) {` `            ``stack.Push(queue.First.Value);` `            ``queue.RemoveFirst();` `        ``}` `        ``while` `(stack.Count > 0) {` `            ``queue.AddLast(stack.Peek());` `            ``stack.Pop();` `        ``}` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``queue = ``new` `LinkedList<``int``>();` `        ``queue.AddLast(10);` `        ``queue.AddLast(20);` `        ``queue.AddLast(30);` `        ``queue.AddLast(40);` `        ``queue.AddLast(50);` `        ``queue.AddLast(60);` `        ``queue.AddLast(70);` `        ``queue.AddLast(80);` `        ``queue.AddLast(90);` `        ``queue.AddLast(100);`   `        ``reversequeue();` `        ``Print();` `    ``}` `}`   `// This code is contributed by Shrikant13`

## Javascript

 ``

Output

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

Time Complexity: O(N), As we need to insert all the elements in the stack and later to the queue.
Auxiliary Space: O(N), Use of stack to store values.

## Reversing a Queue using recursion:

Instead of explicitly using stack goal can be achieved using recursion (recursion at backend will itself maintain stack).

Follow the below steps to implement the idea:

• Recursively perform the following steps:
• If the queue size is 0 return.
• Else pop and store the front element and recur for remaining queue.
• push the current element in the queue.

Thank you Nakshatra Chhillar for suggesting this approach and contributing the code

Below is the implementation of above approach:

## C++

 `// CPP program to reverse a Queue` `#include ` `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``>& q)` `{` `    ``// base case` `    ``if` `(q.size() == 0)` `        ``return``;` `    ``// storing front(first element) of queue` `    ``int` `fr = q.front();`   `    ``// removing front` `    ``q.pop();`   `    ``// asking recursion to reverse the` `    ``// leftover queue` `    ``reverseQueue(q);`   `    ``// placing first element` `    ``// at its correct position` `    ``q.push(fr);` `}`   `// 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);` `}` `// This code is contributed by Nakshatra Chhillar`

## Java

 `/*package whatever //do not write package name here */`   `import` `java.io.*;` `import` `java.util.*;` `class` `GFG {`   `  ``// Utility function to print the queue` `  ``public` `static` `void` `Print(Queue Queue)` `  ``{` `    ``while` `(Queue.size() > ``0``) {` `      ``System.out.print(Queue.peek() + ``" "``);` `      ``Queue.remove();` `    ``}` `  ``}`   `  ``// Function to reverse the queue` `  ``public` `static` `void` `reverseQueue(Queue q)` `  ``{` `    ``// base case` `    ``if` `(q.size() == ``0``)` `      ``return``;` `    ``// storing front(first element) of queue` `    ``int` `fr = q.peek();`   `    ``// removing front` `    ``q.remove();`   `    ``// asking recursion to reverse the` `    ``// leftover queue` `    ``reverseQueue(q);`   `    ``// placing first element` `    ``// at its correct position` `    ``q.add(fr);` `  ``}`   `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``Queue Queue = ``new` `LinkedList<>();`   `    ``Queue.add(``10``);` `    ``Queue.add(``20``);` `    ``Queue.add(``30``);` `    ``Queue.add(``40``);` `    ``Queue.add(``50``);` `    ``Queue.add(``60``);` `    ``Queue.add(``70``);` `    ``Queue.add(``80``);` `    ``Queue.add(``90``);` `    ``Queue.add(``100``);`   `    ``reverseQueue(Queue);` `    ``Print(Queue);` `  ``}` `}`   `// This code is contributed by akashish__`

## Python3

 `# Python3 program to reverse a Queue`   `# Utility function to print the queue` `def` `Print``(Queue):` `    ``while` `(``len``(Queue) > ``0``):` `        ``print``(Queue[``0``],end ``=` `" "``)` `        ``Queue.pop(``0``)`   `# Function to reverse the queue` `def` `reverseQueue(q):` `  `  `    ``# base case` `    ``if` `(``len``(q) ``=``=` `0``):` `        ``return` `    ``# storing front(first element) of queue` `    ``fr ``=` `q[``0``]`   `    ``# removing front` `    ``q.pop(``0``)`   `    ``# asking recursion to reverse the` `    ``# leftover queue` `    ``reverseQueue(q)`   `    ``# placing first element` `    ``# at its correct position` `    ``q.append(fr)`   `# Driver code` `Queue ``=` `[]` `Queue.append(``10``)` `Queue.append(``20``)` `Queue.append(``30``)` `Queue.append(``40``)` `Queue.append(``50``)` `Queue.append(``60``)` `Queue.append(``70``)` `Queue.append(``80``)` `Queue.append(``90``)` `Queue.append(``100``)`   `reverseQueue(Queue)` `Print``(Queue)`   `# This code is contributed by akashish__`

## C#

 `// CPP program to reverse a Queue` `using` `System;` `using` `System.Collections;`   `public` `class` `GFG {`   `    ``// Utility function to print the queue` `    ``public` `static` `void` `Print(Queue Queue)` `    ``{` `        ``while` `(Queue.Count > 0) {` `            ``Console.Write(Queue.Peek());` `            ``Console.Write(``" "``);` `            ``Queue.Dequeue();` `        ``}` `    ``}`   `    ``// Function to reverse the queue` `    ``public` `static` `void` `reverseQueue(Queue q)` `    ``{` `        ``// base case` `        ``if` `(q.Count == 0)` `            ``return``;` `        ``// storing front(first element) of queue` `        ``int` `fr = (``int``)q.Peek();`   `        ``// removing front` `        ``q.Dequeue();`   `        ``// asking recursion to reverse the` `        ``// leftover queue` `        ``reverseQueue(q);`   `        ``// placing first element` `        ``// at its correct position` `        ``q.Enqueue(fr);` `    ``}`   `    ``// Driver code` `    ``static` `public` `void` `Main()` `    ``{`   `        ``Queue Queue = ``new` `Queue();` `        ``Queue.Enqueue(10);` `        ``Queue.Enqueue(20);` `        ``Queue.Enqueue(30);` `        ``Queue.Enqueue(40);` `        ``Queue.Enqueue(50);` `        ``Queue.Enqueue(60);` `        ``Queue.Enqueue(70);` `        ``Queue.Enqueue(80);` `        ``Queue.Enqueue(90);` `        ``Queue.Enqueue(100);`   `        ``reverseQueue(Queue);` `        ``Print(Queue);` `    ``}` `}`

## Javascript

 `// JS program to reverse a Queue`   `// Utility function to print the queue` `function` `Print(Queue) {` `    ``while` `(Queue.length != 0) {` `        ``console.log(Queue);` `        ``Queue.shift();` `    ``}` `}`   `// Function to reverse the queue` `function` `reverseQueue(q) {` `    ``// base case` `    ``if` `(q.length == 0)` `        ``return``;` `    ``// storing front(first element) of queue` `    ``let fr = q;`   `    ``// removing front` `    ``q.shift();`   `    ``// asking recursion to reverse the` `    ``// leftover queue` `    ``reverseQueue(q);`   `    ``// placing first element` `    ``// at its correct position` `    ``q.push(fr);` `}`   `// Driver code` `let 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);`     `// This code is contributed by adityamaharshi21.`

Output

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

Time Complexity: O(N).
Auxiliary Space: O(N). The recursion stack contains all elements of queue at a moment.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next