Reverse Stack Using Recursion
For this particular code we are going to get deeper into recursive techniques. Here we will be simply reversing the order of a stack to print elements in reverse.
Original Stack-> Reverse Stack
1 --top 4 --top
2 3
3 2
4 1
Full code->
#include<bits/stdc++.h>
unsing namespace std;
stack<char> s;
string n;
char insert_at_bottom(char x)
{
if(s.size()==0)
s.push(x);
else
char a = s.top();
s.pop();
insert_at_bottom(x);
s.push(a);
}
char reverse()
{
if(s.size()>0)
char x= s.top();
s.pop();
reverse();
insert_at_bottom(x);
}
int main()
{
s.push(1); s.push(2); s.push(3); s.push(4);
reverse();
while(!s.empty()) //store reverse values in a string
char p= s.top();
s.pop();
n+=p;
cout<<n[3]<<n[2]<<n[1]<<n[0];
return 0;
}