Given a stack containing n elements reverse the stack with the help of an empty stack.
import java.util.Stack;
public class StackReversal {
public static void reverseStack(Stack<Integer> stack) {
if (stack.empty())
return;
int temp = stack.pop();
reverseStack(stack); // popping the elemnt of stack
insertAtBottom(stack, temp);
}
public static void print(Stack<Integer> stack) {
for (int i = 0; i < stack.size(); i++) {
System.out.print(stack.get(i) + " ");
}
}
public static void insertAtBottom(Stack<Integer> stack, int data) {
if (stack.isEmpty()) {
stack.push(data);
return;
}
int temp = stack.pop();
insertAtBottom(stack, data);
stack.push(temp);
}
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);
reverseStack(stack);
print(stack); // printing the element
}
}
Thanks and Regards,
Solution provided by Nilmani Prashanth

