











Java Program to 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
Implentation:
- 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:
- Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)
- 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 CODE :
// Java program to reverse a Queue
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class prepinsta {
static Queue<Integer> que;
static void show()
{
while (!que.isEmpty()) {
System.out.print( que.peek() + “, “);
que.remove();
}
}
// Function to reverse the que
static void queuereverse()
{
Stack<Integer> stk = new Stack<>();
while (!que.isEmpty()) {
stk.add(que.peek());
que.remove();
}
while (!stk.isEmpty()) {
que.add(stk.peek());
stk.pop();
}
}
// Driver code
public static void main(String args[])
{
que = new LinkedList<Integer>();
que.add(5;
que.add(20);
que.add(60);
que.add(40);
queuereverse();
show();
}
}
output:
40 60 20 5
Login/Signup to comment