Infix to Prefix

#include<bits/stdc++.h>
using namespace std;

double calculate(int a, int b, char ch)
{
    if(ch == '+')
        return a+b;
    else if(ch == '-')
        return a-b;
    else if(ch == '*')
        return a*b;
    else if(ch == '/')
        return a/b;
    else if(ch == '^')
           return  pow(a, b);
}

int value(string a)
{
    stack<int>s;
    char ch;
    int i, l = a.size();
    for(i=l-1;i>=0;i--)
    {
        ch = a[i];
        if(ch >= '0' && ch <= '9')
            s.push(ch - '0');
        else
        {
            int a, b, c;
            cout << s.top() << endl;
            b = s.top();
            s.pop();
            a = s.top();
            cout << s.top() << endl;
            s.pop();
            c = calculate(a, b, ch);
            s.push(c);
        }
    }
    return s.top();
}

string reverses(string s)
{
    string a;
    char ch;
    int i, l = s.size();
    for(i=l-1;i>=0;i--)
    {
        ch = s[i];
        if(ch == '(')
            a += ')';
        else if(ch == ')')
            a += '(';
        else
            a += ch;
    }
    return a;
}

int priority(char ch)
{
    if(ch == '^')
        return 3;
    else if(ch == '*' || ch == '/')
        return 2;
    else if(ch == '+' || ch == '-')
        return 1;
    else
        return 0;
}

string converter(string infix)
{
    string pfix = "";
    stack<char>s;
    char ch;
    int i, l = infix.size();
    for(i=0;i<l;i++)
    {
        ch = infix[i];
        if(ch == '(')
            s.push(ch);
        else if(ch == ')')
        {
            while(!s.empty() && s.top() != '(')
            {
                pfix = pfix + s.top();
                s.pop();
            }
            if(!s.empty() && s.top() == '(')
                s.pop();
        }
        else
        {
            int p = priority(ch);
            if(p == 0)
                pfix = pfix + ch;
            else
            {
                if(s.empty())
                    s.push(ch);
                else
                {
                    while(!s.empty() && s.top() != '(' && p <= priority(s.top()))
                    {
                        pfix = pfix + s.top();
                        s.pop();
                    }
                    s.push(ch);
                }
            }
        }
    }
    while(!s.empty())
    {
        pfix = pfix + s.top();
        s.pop();
    }
    return pfix;
}

int main()
{
    string postfix, infix, b, prefix;

    getline(cin , infix);

    b = reverses(infix);

    postfix = converter(b);

    cout << postfix << endl;

    prefix = reverses(postfix);

    cout << prefix << endl;
     int result = value(prefix);
    cout << endl << result << endl;

    return 0;
}

Comments