#include <bits/stdc++.h> // Standard headers (iostream, stack, etc.)
using namespace std; // Standard namespace
// Function to take user input for stack elements
void inputStack(stack<int> &st) { // Pass stack by reference to modify it
cout << "Enter the size : ";
cin >> size; // Get desired size
cout << "Enter stack elements : ";
for(int i=0; i<size; i++) { // Loop to get elements
cin >> temp; // Read element
st.push(temp); // Push onto stack
// Function to print stack elements (consumes the stack copy)
void printStack(stack<int> st) { // Pass by value to print a copy, preserving original
while(!st.empty()) { // Loop until stack is empty
cout << st.top() << " "; // Print top element
st.pop(); // Remove top element
// Helper function: Inserts an element at the bottom of the stack recursively
void insertBottom(stack<int> &st, int data) { // Pass stack by reference
if(st.empty()) { // Base Case: If stack is empty, insert data
int top = st.top(); // Store current top
st.pop(); // Remove current top
insertBottom(st, data); // Recursive call to insert deeper
st.push(top); // Push back stored top (backtracking)
// Main function to reverse the stack recursively
void reverseStack(stack<int> &st) { // Pass stack by reference to modify it
if(st.empty()) { // Base Case: If stack is empty, nothing to reverse
int top = st.top(); // Store current top element
st.pop(); // Remove current top
reverseStack(st); // Recursively reverse the remaining stack
insertBottom(st, top); // Insert the stored top element at the bottom of the now-reversed stack
stack<int> st; // Create a stack
inputStack(st); // Populate stack from user
cout << "Before Reverse : ";
printStack(st); // Print original stack
reverseStack(st); // Call function to reverse the stack
cout << "After Reverse : ";
printStack(st); // Print reversed stack