behnc behnc - 3 months ago 19
C++ Question

How to reverse print stack using recursion?


Please note that it is just reverse printing not reversing a stack


What I want to do is with the help of recursion print the stack i.e bottom to top printing.

I have tried myself but the result is not what I expected.My code looks like this.

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


void print(stack<char>st){
if(st.empty()){return;}
st.pop();
print(st);
cout<<st.top();
}

int main() {
// Assume that I have stack already made....
print(st);
cout<<endl;
}
return 0;
}


Would anybody mind having pointing out my mistake ? Also when I pass stack by reference the results are unexpected.Thanks for support.

Answer

Why don't you store the st.top() at variable and print it later.

void print(stack<char>st)
{
    if(st.empty())
    {
        return;
    }

    char top = st.top();
    st.pop();
    print(st);

    cout<<top<<endl;
}

Let me explain you:-

Suppose, Your stack --> 0, 1

Here, Call Hierarchy

  1. print({0, 1}) { // stack after pop -- {0} print({0}) }
  2. print({0}) { // stack after pop -- {} print ({}) // here you want to print top of empty stack // which gives the exception }