C++ 中缀表达式转后缀表达式算法详解及实现
"C++ 中缀表达式转后缀表达式算法详解及实现"\n\n中缀表达式转后缀表达式是一种常见的算法题,可以使用栈来实现。\n\n首先,我们需要定义操作符的优先级,一般来说,乘除法的优先级高于加减法,括号的优先级最高。\n\n然后,我们遍历中缀表达式的每个字符,根据字符的类型进行相应的操作:\n\n1. 如果是数字,直接输出到后缀表达式中;\n2. 如果是左括号,将左括号压入栈中;\n3. 如果是右括号,将栈中的操作符输出直到遇到左括号,将左括号从栈中弹出;\n4. 如果是操作符,将栈中优先级高于或等于当前操作符的操作符输出,然后将当前操作符压入栈中;\n5. 如果栈不为空,将栈中的操作符全部输出。\n\n下面是一个用C++实现中缀表达式转后缀表达式的例子:\n\ncpp\n#include <iostream>\n#include <stack>\n#include <string>\n\nint getPriority(char op) {\n switch (op) {\n case '+':\n case '-':\n return 1;\n case '*':\n case '/':\n return 2;\n case '(':\n return 3;\n default:\n return 0;\n }\n}\n\nstd::string infixToPostfix(const std::string& infix) {\n std::stack<char> opStack;\n std::string postfix;\n\n for (char ch : infix) {\n if (isdigit(ch)) {\n postfix.push_back(ch);\n } else if (ch == '(') {\n opStack.push(ch);\n } else if (ch == ')') {\n while (!opStack.empty() && opStack.top() != '(') {\n postfix.push_back(opStack.top());\n opStack.pop();\n }\n opStack.pop();\n } else {\n while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(ch)) {\n postfix.push_back(opStack.top());\n opStack.pop();\n }\n opStack.push(ch);\n }\n }\n\n while (!opStack.empty()) {\n postfix.push_back(opStack.top());\n opStack.pop();\n }\n\n return postfix;\n}\n\nint main() {\n std::string infix = "3+4*5/(2-1)";\n std::string postfix = infixToPostfix(infix);\n std::cout << postfix << std::endl;\n\n return 0;\n}\n\n\n上述代码中,我们使用了一个opStack栈来存放操作符,postfix字符串用于存放后缀表达式。getPriority函数用于获取操作符的优先级。\n\n运行上述代码,输出结果为345*21-/+,即中缀表达式3+4*5/(2-1)转换成了后缀表达式。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pQzg 著作权归作者所有。请勿转载和采集!