fork download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. // Function to insert an element at the bottom of the stack
  6. void insertAtBottom(stack<int>& s, int x) {
  7. // If the stack is empty, push the element
  8. if (s.empty()) {
  9. s.push(x);
  10. return;
  11. }
  12.  
  13. // Otherwise, pop the top element
  14. int temp = s.top();
  15. s.pop();
  16.  
  17. // Recursive call to insert at the bottom
  18. insertAtBottom(s, x);
  19.  
  20. // Push the popped element back on top
  21. s.push(temp);
  22. }
  23.  
  24. // Function to reverse the stack
  25. void reverse(stack<int>& s) {
  26. if (!s.empty()) {
  27. // Pop the top element
  28. int x = s.top();
  29. s.pop();
  30.  
  31. // Reverse the remaining stack
  32. reverse(s);
  33.  
  34. // Insert the popped element at the bottom
  35. insertAtBottom(s, x);
  36. }
  37. }
  38.  
  39. int main() {
  40. stack<int> s;
  41.  
  42. // Pushing elements to the stack: 1 2 3 4 (bottom to top)
  43. s.push(1);
  44. s.push(2);
  45. s.push(3);
  46. s.push(4);
  47.  
  48. // Reversing the stack
  49. reverse(s);
  50.  
  51. // Printing the reversed stack
  52. while (!s.empty()) {
  53. cout << s.top() << " ";
  54. s.pop();
  55. }
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
1 2 3 4