码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-10-06 20:08:42      阅读:25      评论:0      收藏:0      [点我收藏+]

标签:mes   ace   +=   stack   style   its   ||   tac   while   

#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");
}

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

标签:mes   ace   +=   stack   style   its   ||   tac   while   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!