// Function to insert an element at the bottom of the stack 📦
void insertStack(stack<int>& stack, int x) {
// Base case: if the stack is empty, just push the element 🤔
if (stack.empty()) {
stack.push(x); // Stack: [x] 👍
return;
}
// Store the top element and pop it from the stack 💸
int num = stack.top(); // num = top element 👀
stack.pop(); // Remove the top element 🔥
// Recursive call to insert the element at the bottom 🔄
insertStack(stack, x); // Insert x at the bottom 🔩
// Push the stored top element back into the stack 💪
stack.push(num); // Stack: [..., x, num] 👍
}
// Function to reverse the stack 🔙
void reverseStack(stack<int>& stack) {
// Base case: if the stack is empty, do nothing 🙅♂️
if (stack.empty()) {
return;
}
// Store the top element and pop it from the stack 💸
int top = stack.top(); // top = top element 👀
stack.pop(); // Remove the top element 🔥
// Recursive call to reverse the remaining stack 🔄
reverseStack(stack); // Reverse the remaining stack 🔙
// Insert the stored top element at the bottom of the stack 📦
insertStack(stack, top); // Insert top at the bottom 🔩
}
// Example usage:
// Take stack: [1, 2] 📈
// 1. top = 2 👀
// then remove the 2 from the top 🔥
// and make a recursive call 🔄
// now top = 1 👀
// again remove the top 🔥
// now stack becomes empty 📦
// Now make a recursive call to insertStack to insert element 📦
// Stack: [] 📦
// Stack: [1] 👍 and return
// Again make a call and now stack: [1] 📈
// top = 1 👀
// In next iteration if Stack: [1] 🤔
// pop the top element to insert new element 🔥
// Now 1 is pop and stack becomes empty 📦
// element 2 is push into stack 🔩
// and then 1 is push into stack 👍
// Stack becomes [2, 1] 📈