I am trying to flip the stack using recursion:
I can print stack elements in reverse order. But if I try to push the inverse elements, it does not work.
Let the stack be [0,1,2,3,4]. 4 - top .
Here is what I tried:
private static void reverseStack(Stack<Integer> stack) {
if (!stack.isEmpty()){
int n=stack.pop();
reverseStack(stack);
System.out.println(n);
}
}
With this, I get the correct conclusion.
Output is :
0
1
2
3
4
This is what I expected.
If I try to return these elements to the stack, I will return to the same stack without contacting:
This is the code used to reverse:
private static void reverseStack(Stack<Integer> stack) {
if (!stack.isEmpty()){
int n=stack.pop();
reverseStack(stack);
System.out.println(n);
stack.push(n);
}
}
This is the step of the step obtained from this code:
private static void reverseStack(Stack<Integer> stack) {
if (!stack.isEmpty()){
int n=stack.pop();
System.out.println(stack);
reverseStack(stack);
System.out.println(n);
stack.push(n);
}
}

We can clearly see that the output stack is the same as the input stack, but still the elements are printed in reverse order. Where am I doing wrong?