infix2postfix

来源:互联网 发布:medusa 软件 编辑:程序博客网 时间:2024/06/01 09:20
#include <iostream>#include <stack>using namespace std;int main(){    stack<char> s; // use a stack to store the character of the equation    string equation; // store the whole equation    getline (cin, equation);    int cur = 0; // the current position in the equation    while (cur < equation.size())    {        while (equation[cur] == ' ')            cur++;        if (equation[cur] >= 'a' && equation[cur] <= 'z')            cout<< equation[cur] << " ";        else if (equation[cur] == ')')        {            while(!s.empty() && s.top() != '(') // if equation[cur] equals ')', then pop out all the character until '('            {                cout<< s.top() << " ";                s.pop();            }            s.pop(); // pop out the '('        }           else if (equation[cur] == '(') // '(' has the highest priority, put it into the stack directly            s.push(equation[cur]);         else if (equation[cur] == '^')  // '^' has the highest priority except for the parenthesis            s.push(equation[cur]);         else if (equation[cur] == '*' || equation[cur] == '/') //        {            while(!s.empty() && s.top() != '+'&& s.top() != '-' && s.top() != '(') //'*' and '/' have the same priority            {                cout<< s.top() << " ";                 s.pop();            }            s.push(equation[cur]);        }        else if (equation[cur] == '+' || equation[cur] == '-') //'+' and '-' have the same priority        {            while(!s.empty() && s.top() != '(' )            {                cout<< s.top() << " ";                s.pop();            }            s.push(equation[cur]);         }     cur++; // to process the next character    }    while (!s.empty())    {        cout << s.top() << " ";        s.pop();    }    return 0;}
0 0
原创粉丝点击