Uva 727 Solution

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

int priority(int 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 postfix = "";
    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() != '(')
            {
                postfix += s.top();
                s.pop();
            }
            if(!s.empty() && s.top() == '(')
                s.pop();
        }
        else
        {
            int p = priority(ch);
            if(p == 0)
                postfix += ch;
            else
            {
                if(s.empty())
                    s.push(ch);
                else
                {
                    while(!s.empty() && s.top() != '(' && p <= priority(s.top()))
                    {
                        postfix += s.top();
                        s.pop();
                    }
                    s.push(ch);
                }
            }
        }
    }
    while(!s.empty())
    {
        postfix += s.top();
        s.pop();
    }
    return postfix;
}

int main()
{
   char an[70];
   int n, i, c = 1;
   cin >> n;
   cin.ignore();
   cin.ignore();
    while(n--)
    {
        if(c++ > 1)
            cout << endl;

        string ifix = "";
        while(gets(an))
        {
            if(strcmp(an,"\n"))
                break;
            ifix = ifix + an;
        }
        string pfix = converter(ifix);
        cout << pfix << endl;
    }
    return 0;
}

Comments