-3

Im trying to reverse a stack, by simply putting it into another stack from the top, so that it could be reversed. Here is the code:

#include <bits/stdc++.h>
using namespace std;

stack<char> Reverse(stack<char> &st) {
  stack<char> sk;
  if (st.empty()) return sk;
  sk.push(st.top());
  st.pop();
  Reverse(st);
}
int main() {
  stack<char> st;
  st.push('a');
  st.push('b');
  st.push('c');
  st.push('d');
  stack<char> sk = Reverse(st);
}

Please help me find the error.

churill
  • 9,299
  • 3
  • 13
  • 23
  • 1
    Missing return for one path, and `sk` is "unused". – Jarod42 Dec 12 '20 at 09:56
  • 1
    What will `Reverse` return when `st.empty()` is false? And what happens with the return value of `Reverse(st);` in the recursive call? – churill Dec 12 '20 at 09:57
  • 1
    OT: Please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) Habits, good and bad, tend to stick. So even if you say "it's just for a small example so it's no big deal", if that example have bad habits you will get used to those bad habits. Better use good habits everywhere, even for small examples. – Some programmer dude Dec 12 '20 at 09:58
  • You should tell us what the error is / how it demonstrates itsefl, we can help you fix it. – dedObed Dec 12 '20 at 10:19

1 Answers1

0

You might use:

std::stack<char> Reverse(std::stack<char> &st, std::stack<char>&& res = {}) {
  if (st.empty()) return std::move(res);
  res.push(st.top());
  st.pop();
  return Reverse(st, std::move(res));
}

Demo

Jarod42
  • 173,454
  • 13
  • 146
  • 250