reverse a stack using recursion

Solutions on MaxInterview for reverse a stack using recursion by the best coders in the world

showing results for - "reverse a stack using recursion"
Lena
15 Oct 2019
1#include <bits/stdc++.h>
2
3using namespace std;
4void insert(stack<int>&s,int e)
5{
6    if(s.size()==0)
7    {
8        s.push(e);
9        return;
10    }
11    int temp=s.top();
12    s.pop();
13    insert(s,e);
14    s.push(temp);
15}
16void rever(stack<int>&s)
17{
18    if(s.size()==0)
19    {
20        return;
21    }
22    int temp=s.top();
23    s.pop();
24    rever(s);
25    insert(s,temp);
26}
27int main()
28{
29    int n;
30    cin>>n;
31    stack<int>st;
32    for(int i=0;i<n;i++)
33    {
34
35        int a;
36        cin>>a;
37        st.push(a);
38    }
39    rever(st);
40    while(!st.empty())
41    {
42        cout<<st.top()<<endl;
43        st.pop();
44    }
45    return 0;
46}
47