中缀表达式转为后缀表达式

#include <bits/stdc++.h>
using namespace std;
stack<char> stack_op;
stack<int> stack_num;
char str[10000];
string change;
int pow(int x, int y)
{
    int ans = 1;
    while (y--)
        ans *= x;
    return ans;
}
void cal(char op)
{
    int a = stack_num.top();
    stack_num.pop();
    change += op;
    switch (op)
    {
    case '+':
        stack_num.top() += a;
        break;
    case '-':
        stack_num.top() -= a;
        break;
    case '*':
        stack_num.top() *= a;
        break;
    case '/':
        stack_num.top() /= a;
        break;
    case '^':
        stack_num.top() = pow(stack_num.top(), a);
    }
}
int ord(char op)
{
    if (op == '(')
        return 1;
    if (op == '+' || op == '-')
        return 2;
    if (op == '*' || op == '/')
        return 3;
    if (op == '^')
        return 4;
    return 0;
}
bool check(char op)
{
    if (stack_op.empty() || op == '(')
        return false;
    int now = ord(op), top = ord(stack_op.top());
    if (!now)
    {
        if (top == 1)
        {
            stack_op.pop();
            return false;
        }
        else
            return true;
    }
    return now <= top;
}
int main()
{
    gets(str);
    for (int i = 0; str[i]; ++i)
    {
        if (isdigit(str[i]))
        {
            int num = str[i] - '0';
            while (isdigit(str[i + 1]))
                num = num * 10 + str[++i] - '0';
            stack_num.push(num);
            change = change + to_string(num);
        }
        else
        {
            while (check(str[i]))
                cal(stack_op.top()), stack_op.pop();
            if (str[i] != ')')
                stack_op.push(str[i]);
        }
    }
    while (!stack_op.empty())
        cal(stack_op.top()), stack_op.pop();
    cout << change << endl << stack_num.top();
    system("pause");
}
posted @ 2020-10-03 08:49  Vivid-BinGo  阅读(132)  评论(0编辑  收藏  举报