Tuesday, September 13, 2016

Reverse of a string using stack

Sol :
We declare stack as data type using STL library. All the declarations can be done accordingly. We push all the elements and after pushing all to the stack, we assign the top element to that array that will overwrite the values of the old array with new array values and popping after every assignment.  
Code :
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;

void Reverse(char c[], int n){
    stack<char> S;
    for(int i=0;i<=n-1;i++){
        S.push(c[i]);
    }
    for(int i=0;i<=n-1;i++){
        c[i]  = S.top();
        S.pop();
    }
}
int main(){
    char C[51];
    cout<<"Enter a string: ";
    cin>>C;
    Reverse(C, strlen(C));
    cout<<C<<endl;
    return 0;
}

No comments:

Post a Comment

Search This Blog