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.
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); } }
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]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions