VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reversing-queue-using-recursion/

⇱ Reversing a queue using recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reversing a queue using recursion

Last Updated : 17 Mar, 2025

Given a queue, reverse the elements of the queue using recursion. The task is to reverse the order of the elements in the queue and return the reversed queue.

Standard operations allowed:

  • enqueue(x): Adds an item x to the rear of the queue.
  • dequeue(): Removes an item from the front of the queue.
  • empty(): Checks if the queue is empty or not.

Examples :

Input : Q = [5, 24, 9, 6, 8, 4, 1, 8, 3, 6]
Output : Q = [6, 3, 8, 1, 4, 8, 6, 9, 24, 5]
Explanation : Output queue is the reverse of the input queue.

Input : Q = [8, 7, 2, 5, 1]
Output : Q = [1, 5, 2, 7, 8]
Explanation : Output queue is the reverse of the input queue.

Recursive Algorithm :

  1. The pop element from the queue if the queue has elements otherwise return empty queue.
  2. Call reverseQueue function for the remaining queue.
  3. Push the popped element in the resultant reversed queue.

Pseudo Code :

queue reverseFunction(queue)
{
if (queue is empty)
return queue;
else {
data = queue.front()
queue.pop()
queue = reverseFunction(queue);
q.push(data);
return queue;
}
}

Implementation:


Output
100 90 80 58 92 85 45 30 27 56 

Complexity analysis:

  • Time Complexity: O(n). 
  • Auxiliary Space: O(n), since recursion uses stack internally
Comment
Article Tags:
Article Tags: