中缀表达式转后缀表达式

 

#include <iostream>
#include <map>
#include <stack>
#include <string>

using namespace std;

map<char,int> priorityIn{
    {'+',3},
    {'-',3},
    {'*',5},
    {'/',5},
    {'(',1},
    {')',6}
};
map<char,int> priorityOut{
    {'+',2},
    {'-',2},
    {'*',4},
    {'/',4},
    {'(',6},
    {')',1}
};

int main()
{
    string in;
    stack<char> op;
    char c;
    map<char, int>::iterator iter;
    cin >> in;
    for (int i = 0; i < in.length(); ++i)
    {
        c = in[i];
        iter = priorityIn.find(c);
        if (iter != priorityIn.end())
        {
            if (op.empty())
                op.push(c);
            else
            {
                if (priorityOut.at(c) >= priorityIn.at(op.top()))
                    op.push(c);
                else
                {
                    while(!op.empty() && priorityOut.at(c) < priorityIn.at(op.top()))
                    {
                        cout << op.top();
                        op.pop();
                    }
                    if (c == ')')
                        op.pop();
                    else
                        op.push(c);
                }
            }
        }
        else
            cout << c;
    }
    while(!op.empty())
    {
        cout << op.top();
        op.pop();
    }
    return 0;
}

 

posted @ 2020-10-19 15:23  Joey_blog  阅读(84)  评论(0编辑  收藏  举报