跳到正文

个人记录

中缀表达式转后缀表达式

Forever_Rain约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

一年前转载,忘记谁写的了。

C++
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int prio(char op) //运算符优先级排序
{
    int priority;
    if (op == '*' || op == '/')
        priority = 2;
    if (op == '+' || op == '-')
        priority = 1;
    if (op == '(')
        priority = 0;
    return priority;
}
bool Trans(string &str,string &str1) //引用传递
{
    stack<char> s;
    int i;
    for (i = 0; i<str.size(); i++)
    {
        if (str[i] >= '0' && str[i] <= '9'||str[i] >= 'a' && str[i] <= 'z')
        {
            str1+=str[i];
        }
        else
        {
            if (s.empty())
                s.push(str[i]);
            else if (str[i] == '(')
                s.push(str[i]);
            else if (str[i] == ')')
            {
                while (s.top() != '(')
                {
                    str1+= s.top();
                    s.pop();
                }
                s.pop();
            }
            else
            {
                while (prio(str[i]) <= prio(s.top()))
                {
                    str1+= s.top();
                    s.pop();
                    if (s.empty())
                        break;
                }
                s.push(str[i]);
            }
        }
    }
    while (!s.empty())
    {
        str1+= s.top();
        s.pop();
    }
    return true;
}
int main()
{
    string infix;
    string postfix;
    cout << "请输入中缀表达式:" << infix << endl;
    cin >> infix;
    Trans(infix,postfix);
    cout << "后缀表达式为:" << postfix << endl;
    system("pause");
    return 0;
}
原文