首页 > 其他 > 详细

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

时间:2020-10-03 09:40:27      阅读:39      评论:0      收藏:0      [点我收藏+]
#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");
}

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

原文:https://www.cnblogs.com/VividBinGo/p/13763480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!