How to Reverse a Stack in Java
How to Reverse a Stack in Java
Reversing a stack in Java means reversing the order of elements in a stack. A stack is a data structure that follows the Last-In-First-Out (LIFO) principle, which means that the last element added to the stack is the first one to be removed. To reverse a stack, you need to reverse the order of the elements so that the first element becomes the last one, the second element becomes the second-to-last one, and so on.
To reverse a stack in Java, you can use a temporary stack to hold the reversed elements. Here's an example implementation:
import java.util.*;
public class ReverseStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("Original stack: " + stack);
Stack<Integer> reversedStack = reverseStack(stack);
System.out.println("Reversed stack: " + reversedStack);
}
public static Stack<Integer> reverseStack(Stack<Integer> stack) {
Stack<Integer> tempStack = new Stack<>();
while (!stack.isEmpty()) {
int element = stack.pop();
tempStack.push(element);
}
return tempStack;
}
}
In this example, we create a stack with the values 1 to 5 and print the original stack. We then call the reverseStack() method to reverse the stack and print the reversed stack.
The reverseStack() method takes the original stack as an argument and creates a new temporary stack. It then pops elements from the original stack and pushes them onto the temporary stack, effectively reversing the order of the elements. Finally, it returns the reversed stack.