Write a Java program to Reverse the elements of a queue using recursion


The Java code demonstrates how to reverse the order of elements in a queue using recursion. The reverseQueue() method uses recursion to reverse the queue.

  • A Queue interface is implemented using the LinkedList class to create a queue named queue to store integers.
  • Several integer elements (10, 20, 30, 40, 50) are added to the queue using the offer() method.
  • The original order of elements in the queue is printed using System.out.println().
  • The reverseQueue() method is called with the queue as an argument. This method uses recursion to reverse the order of elements in the queue.
  • The reversed order of elements in the queue is printed using System.out.println().

The reverseQueue() method is the recursive function responsible for reversing the queue. It works as follows:

  • The method checks if the queue is empty. If it is, the function returns, as there is no need to perform any further operations.
  • If the queue is not empty, the front element of the queue is removed using the poll() method, and its value is stored in the variable frontElement.
  • The reverseQueue() method is called recursively on the remaining queue.
  • After the recursive call returns and the remaining elements of the queue have been reversed, the frontElement is added back to the queue using the offer() method.
  • The recursion continues until all elements have been removed and added back, effectively reversing the order of elements in the queue

Source Code

import java.util.*;
public class ReverseQueueRecursion
{
	public static void reverseQueue(Queue<Integer> queue)
	{
		if (queue.isEmpty())
		{
			return;
		}
 
		int frontElement = queue.poll();
		reverseQueue(queue);
		queue.offer(frontElement);
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(10);
		queue.offer(20);
		queue.offer(30);
		queue.offer(40);
		queue.offer(50);
 
		System.out.println("Original Queue : " + queue);
		reverseQueue(queue);
		System.out.println("Reversed Queue : " + queue);
	}
}
 

Output

Original Queue : [10, 20, 30, 40, 50]
Reversed Queue : [50, 40, 30, 20, 10]

Example Programs