Java Program to Reverse a Queue

reverse a queue

How to Reverse a Queue in  Java programming language?

In this we will learn how to write a Java Program to Reverse a Queue. In this  page, we will learn to code and perform the task.
For example :- Input : 5 20 60 40
Output : 40 60 20 5 


  • First we will create a Queue.
  • Initialize Queue by taking input from user.
  • Call the reverse function.
  •  The stack could help in approaching this problem. This will be a two-step process:

    1. Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)
    2. 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)
  • Call show function for printing the data.


// Java program to reverse a Queue 
import java.util.LinkedList; 
import java.util.Queue; 
import java.util.Stack; 

public class prepinsta { 
    static Queue<Integerque

    static void show() 
        while (!que.isEmpty()) { 
            System.out.printque.peek() + “, “); 

    // Function to reverse the que 
    static void queuereverse() 
        Stack<Integerstk = new Stack<>(); 
        while (!que.isEmpty()) { 
        while (!stk.isEmpty()) { 

    // Driver code 
    public static void main(String args[]) 
        que = new LinkedList<Integer>(); 


40 60 20 5