Solved programming problem

Convert Postfix Expression to Prefix Expression in C++.

Source code

#include<bits/stdc++.h>

#include<string>

#include<stdio.h>

#include<stdlib.h>

/*postfix to prefix*/

using namespace std;

string convertPostToPre(string post)

{

    stack<string> stk;

    string pre;

    for(int i=0; i<post.size(); i++)

    {

        if(post[i]=='+' || post[i]=='/' ||post[i]=='*' ||post[i]=='-' || post[i]=='^')

        {

            string t = string(1, post[i]);

            string a = stk.top();

            stk.pop();

            string b = stk.top();

            stk.pop();

            t  +=b+a;

            stk.push(t);

        }

        else

        {

            stk.push(string(1, post[i]));

        }

    }

    return stk.top();

}

int main()

{

    string post;

    cout<<"
Enter Postfix: ";

    cin>>post;

    cout<<"
Prefix: "<<convertPostToPre(post)<<endl;

}

Output

Enter Postfix: ab+

Prefix: +ab

Join the discussion

Add your comment