Skip to main content

Reverse stack in C++


#include<bits/stdc++.h>

using namespace std;

void rev(string s){
    stack<string> st;
    for (int i = 0; i <s.length(); i++)
    {
       string word = "";
       while(s[i]!=' ' && i<s.length()){
           word+=s[i];
           i++;
       }
       st.push(word);
    }
    while(!st.empty()){
        cout<<st.top()<<" ";
        st.pop();
    }
   
}
void InsertatBottom(stack<int> &st, int ele){
    if(st.empty()){
        st.push(ele);
        return;
    }
    int topele = st.top();
    st.pop();
    InsertatBottom(st,ele);
    st.push(topele);
}

void reverse(stack<int> &st){
   
    if(st.empty()){
        return;
    }

    int ele = st.top();
    st.pop();
    reverse(st);
    InsertatBottom(st, ele);
}
void display(stack<int> &st){
    while(!st.empty()){
        cout<<st.top()<<" ";
        st.pop();
    }
}
int main()
{
    /* It will reverse the string   */
  string s = "What are you doing?";

    rev(s);
   


        /* It's for integer        */      
//     stack<int> st ;
//     st.push(4);
//     st.push(3);
//     st.push(2);
//     st.push(1);

//    cout<<"After Reverse"<<endl;
//    reverse(st);
//    display(st);

    return 0;
}

Comments