You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

中缀转后缀栈实现C++代码翻译及技术问询规范化需求

基于栈实现的中缀表达式转后缀表达式(C++实现)

没问题,这就给你呈上基于栈实现的中缀表达式转后缀表达式的C++完整代码,所有注释已经翻译成中文,同时严格保留了技术术语、代码逻辑和符号规则:

#include<iostream> 
#include<cstring> 
#include<string> 
#include "linkedStack.h" 
#include <fstream> 
#include <iomanip> 
#include "ArgumentManager.h" 
using namespace std; 

// 该函数用于判定并返回运算符的优先级
int getPrecedence(char ch) 
{ 
    switch (ch) 
    { 
        case '/': return 2; break; 
        case '*': return 2; break; 
        case '+': return 1; break; 
        case '-': return 1; break; 
        default: return 0; // 操作数、括号等非运算符优先级为0
    } 
} 

// 将中缀表达式转换为后缀表达式的核心函数
string infixToPostfix(const string& expression)
{
    linkedStack<char> opStack; // 用于存储运算符的栈
    string postfixExp; // 存储转换后的后缀表达式

    for (char ch : expression)
    {
        // 如果是字母或数字(操作数),直接加入后缀表达式
        if (isalnum(ch))
        {
            postfixExp += ch;
        }
        // 如果是左括号,直接压入栈中
        else if (ch == '(')
        {
            opStack.push(ch);
        }
        // 如果是右括号,弹出栈中元素直到遇到左括号
        else if (ch == ')')
        {
            while (!opStack.isEmpty() && opStack.top() != '(')
            {
                postfixExp += opStack.top();
                opStack.pop();
            }
            opStack.pop(); // 弹出左括号,不加入后缀表达式
        }
        // 如果是运算符
        else
        {
            // 弹出栈中优先级大于等于当前运算符的元素,加入后缀表达式
            while (!opStack.isEmpty() && getPrecedence(opStack.top()) >= getPrecedence(ch))
            {
                postfixExp += opStack.top();
                opStack.pop();
            }
            opStack.push(ch); // 将当前运算符压入栈
        }
    }

    // 弹出栈中剩余的所有运算符,加入后缀表达式
    while (!opStack.isEmpty())
    {
        postfixExp += opStack.top();
        opStack.pop();
    }

    return postfixExp;
}

// 示例主函数(可根据需求调整)
int main(int argc, char* argv[])
{
    ArgumentManager am(argc, argv);
    string inputFile = am.get("input");
    string outputFile = am.get("output");

    ifstream in(inputFile);
    ofstream out(outputFile);

    string infixExp;
    getline(in, infixExp);

    string postfixExp = infixToPostfix(infixExp);
    out << postfixExp << endl;

    in.close();
    out.close();

    return 0;
}

代码关键说明

  • 优先级判定函数getPrecedence:定义了四则运算符的优先级,*和/优先级高于+和-,非运算符(如操作数、括号)优先级设为0,确保转换逻辑正确。
  • 核心转换逻辑:严格遵循中缀转后缀的经典算法规则,通过栈来临时存储运算符,保证运算顺序符合优先级要求。
  • 文件读写支持:通过ArgumentManager类处理命令行参数,实现从指定输入文件读取中缀表达式,转换后写入输出文件,适合批量处理场景。

内容的提问来源于stack exchange,提问作者MChung93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:28:26