The Call Stack
Since we can't use an external array or stack, we use the System Call Stack! We recursively pop elements until the stack is empty, storing the popped values in local variables (`temp`) at each recursive level.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Reverse a stack using ONLY recursion. You are not allowed to use any loops or auxiliary data structures (like another stack or queue).
Since we can't use an external array or stack, we use the System Call Stack! We recursively pop elements until the stack is empty, storing the popped values in local variables (`temp`) at each recursive level.
The `reverse()` function empties the entire stack. On its way back up (as the recursion unwinds), it takes the element it popped and asks `insertAtBottom` to put it at the very bottom.
Because the top is blocked by other elements, this function recursively pops everything out of the way, pushes the desired element at the absolute bottom, and then puts everything back on top.