postfix2infix

来源:互联网 发布:linux vim 没有颜色 编辑:程序博客网 时间:2024/06/04 21:16
#include <iostream>#include <stack>#include <string>#include <sstream>using namespace std;int main(){    stack<string> s; // use a stack to store the current answer    string equation; // the whole equation    string lhs, rhs; // represent the left hand side and right hand side of an operator    getline (cin, equation);    int cur = 0; // the current position in the equation    while (cur < equation.size())    {        while (equation[cur] == ' ') // skip the blank space            cur++;        if (equation[cur] >= 'a' && equation[cur] <= 'z') //if equation[cur] is a letter, just put it into s        {            stringstream ss; // change the singal character into string to put it into the s            ss << equation[cur];            s.push(ss.str());        }        // else if equation[cur] is an operator, pop out its lhs and rhs, then combine them into a new sub-equation        else if (equation[cur] == '+' || equation[cur] == '-' || equation[cur] == '*'                    || equation[cur] == '/' || equation[cur] == '^')        {            rhs = s.top(); // right hand side of the operator            s.pop();             lhs = s.top(); // left hand side of the operator            s.pop();            s.push("(" + lhs + " " + equation[cur] + " " + rhs + ")"); // put the sub-equation into the stack s        }    cur++; // to process the next character    }    cout << s.top() << endl; // at last the stack s only contains the final infix equation    return 0;}
0 0
原创粉丝点击