Reverse stack in O (n) without extra-space does not occur

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);
        }
    }

Conclusion

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?

+4
4

, sysout (System.out.println) , . . , , 0,1,2,3,4 , [0,1,2,3,4] . pic, :) http://imgur.com/a/5Omx9 enter image description here

+1

, , . ( , ).

, 2- , @Scott @Berkley, . .

while(!stack.isEmpty()) {
 reversedStack.push(stack.pop());            
}
+3

, , . " ", . , , , .

+2

, . , .

First call ([0,1,2,3,4])
int n = 4
Second call ([0,1,2,3])
int n = 3
Third call ([0,1,2])
int n = 2
Fourth call ([0,1])
int n = 1
Fifth call ([0])
int n = 0
Sixth call ([])
empty is reached, return
add 0 to stack then return ([0])
add 1 to stack then return ([0,1])
add 2 to stack then return ([0,1,2])
add 3 to stack then return ([0,1,2,3])
add 4 to stack then return ([0,1,2,3,4])

, .

while(!stack.isEmpty()) {
 int n = stack.pop();
 stack2.push(n);            
}
+1

Source: https://habr.com/ru/post/1684318/


All Articles