运算符装换(中缀转后缀)

#include<iostream>
#include<algorithm>
#include<stack>
#include<map>
using namespace std;

stack<char>st;
map<char, int>Rank;//进行优先级比较

int main()
{
    Rank['+'] = Rank['-'] = 1;
    Rank['*'] = Rank['/'] = 2;
    string str;//将题目中按照字符串形式输入
    cin >> str;
    bool isfirst = true;//用于控制输入空格
    for (int i = 0; i < str.size(); i++)
    {
        //下面是三种情况
        //(1)数字(2)小数点(3)如果第一个位置或者前面是左括号,并且是正负号
        if (isdigit(str[i]) || (str[i] == '.') || ((i == 0 || str[i - 1] == '(') && (str[i] == '+' || str[i] == '-')))
        {
            if (!isfirst)
                cout << " ";
            if (str[i] != '+')//负号和数直接输出
                cout << str[i];
            while (str[i + 1] == '.' || isdigit(str[i + 1]))
            {
                cout << str[++i];
            }
            isfirst = false;
        }
        else {
            if (str[i] == '(')
            {
                st.push(str[i]);
            }
            else if (str[i] == ')')
            {
                while (!st.empty() && st.top() != '(')
                {
                    cout << " " << st.top();
                    st.pop();
                }
                st.pop();
            }
            else if (st.empty() || Rank[str[i]] > Rank[st.top()]) {
                //优先级高得直接入栈
                st.push(str[i]);
            }
            else {
                //优先级低进先把前面的先出栈,然后进栈
                while (!st.empty() && st.top() != '(')
                {
                    cout << " " << st.top();
                    st.pop();
                }
                st.push(str[i]);
            }
        }
    }

    while (!st.empty())
    {
        cout << " " << st.top();
        st.pop();
    }
    return 0;
}

 

posted @ 2024-01-22 16:30  敲代码的6  阅读(11)  评论(0)    收藏  举报