1027. Reverse a Stack

You are given a stack of integers. Your task is to reverse the stack using recursion. You may only use standard stack operations (push, pop, top/peek, isEmpty). You are not allowed to use any loop constructs or additional data structures like arrays or queues.

Your solution must modify the input stack in-place to reverse the order of its elements.

Example 1:

Input: stack = [4, 1, 3, 2]

Output: [2, 3, 1, 4]

Example 2:

Input: stack = [10, 20, -5, 7, 15]

Output: [15, 7, -5, 20, 10]

Now Your Turn!

Pick the correct output for the given input

Input: stack = [100, 90, 80, 70, 60]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= N <= 100 (where N is the number of elements in the stack)
  • Must use only recursion (no loops or built-in reverse methods)
  • Auxiliary space allowed: O(N) (due to recursion stack)
0
class Solution {
public:
void reverseStack(stack<int> &st) {
// Your code goes here
}
};
Test Case

Input:

Stack