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.
stack<T>is designed to hide its implementation. You'd have to write your own stack based on avector<T>, say. You're getting an error because when youpopthe last element, the stack is empty, then you're trying to printst.top()which no longer exists. Move thecoutto before thepop.stack<T>won't support what you want. You have to write your ownMyStackclass. Also, by callingpopyou're removing the top of the stack - you may just want to print the stack without emptying it.