Write a Java program to Reverse the order of elements in a queue without using any additional data structures


The Java code demonstrates how to reverse the order of elements in a queue using a stack. The reverseQueue() method takes a Queue of integers as input, and it reverses the order of elements within that queue.

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

Source Code

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
 
public class ReverseQueue
{
	public static void reverseQueue(Queue<Integer> queue)
	{
		Stack<Integer> stack = new Stack<>();
		while (!queue.isEmpty())
		{
			stack.push(queue.poll());
		}
		while (!stack.isEmpty())
		{
			queue.add(stack.pop());
		}
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.add(10);
		queue.add(20);
		queue.add(30);
		queue.add(40);
		queue.add(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