Write a Java program to Reverse Queue using a Stack


The Java code is an example of how to reverse the elements of a queue using a stack. The program uses a Queue implemented with a LinkedList and a Stack from the java.util package.

  • First, a Queue<Integer>l named queue and a Stack<Integer> named stack are created to store integers.
  • Ten integers (10 to 100) are added to the queue using the offer() method.
  • The original state of the queue is printed.
  • The queue is reversed using a stack. To reverse the queue, the program follows these steps:
    • While the queue is not empty, it dequeues the elements from the queue and pushes them onto the stack using the push() method. This effectively reverses the order of the elements.
    • After all elements have been dequeued from the queue and pushed into the stack, the stack now contains the elements in reversed order.
  • Finally, the reversed elements are pushed back into the queue using the offer() method.
  • The program prints the queue after reversal, which will display the elements in reversed order compared to the original queue.

Source Code

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
 
public class Reverse_Queue
{
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		Stack<Integer> stack = new Stack<>();
 
		queue.offer(10);
		queue.offer(20);
		queue.offer(30);
		queue.offer(40);
		queue.offer(50);
		queue.offer(60);
		queue.offer(70);
		queue.offer(80);
		queue.offer(90);
		queue.offer(100);
 
		System.out.println("Queue Before Reversal : " + queue);
 
		// Reverse the queue using a stack
		while(!queue.isEmpty())
		{
			stack.push(queue.poll());
		}
 
		while(!stack.isEmpty())
		{
			queue.offer(stack.pop());
		}
 
		System.out.println("Queue After Reversal : " + queue);
    }
}
 

Output

Queue Before Reversal : [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Queue After Reversal : [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

Example Programs