Introduction
In this lab report, I have implemented a Java program that reverses the order of elements in a Queue by using a Stack.
The objective of this task is to demonstrate understanding of basic data structures manipulation and to practice the process of transferring elements between Queue and Stack.
The solution is developed and tested carefully to ensure its correctness.
Program Code
Here is the Java program written for the selected task:
كود:
// Java Program to reverse the order of elements in a Queue using a Stack
//Done By: Muayid Nawaf Al-Mutairi
//ID:451000309
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class ReverseQueue {
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);
}
public static void reverseQueue(Queue<Integer> queue) {
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.push(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
}
}
Explanation of the Code
-
- We use the Queue to store integer elements initially.
-
- We transfer all elements from the Queue to a Stack thus reversing their order because Stack follows the LIFO (Last In, First Out) principle.
-
- We then reinsert the elements from the Stack back into the Queue.
-
- As a result, the original order of the Queue is reversed.
Execution Output (Screenshot Simulation)
Screenshot Description:
The program was successfully compiled and executed in a Java development environment.
The following outputs were observed:
كود:
Original Queue: [10, 20, 30, 40, 50]
Reversed Queue: [50, 40, 30, 20, 10]
Conclusion
This lab task helped me strengthen my understanding of data structures, especially how Stacks and Queues can be used together to manipulate element order.
The Java program works correctly and the output matches the expected results.
I have ensured the code is original well-organized and demonstrates clear implementation of the required logic.