C++ 中缀表达式转后缀表达式详解及代码实现
"C++ 中缀表达式转后缀表达式详解及代码实现"\n\n中缀表达式转后缀表达式是利用栈来实现的。\n\n具体步骤如下:\n\n1. 创建一个栈,用于存储运算符和括号。\n2. 创建一个空字符串,用于存储后缀表达式。\n3. 从左到右遍历中缀表达式的每个字符:\n - 如果是操作数,直接将其添加到后缀表达式字符串中。\n - 如果是运算符或括号:\n - 如果栈为空,或者栈顶元素是左括号'(',则将运算符或括号直接入栈。\n - 如果栈不为空,并且栈顶元素不是左括号'(',则将栈顶元素弹出并添加到后缀表达式字符串中,直到栈为空或者栈顶元素是左括号'(',最后将运算符或括号入栈。\n - 如果是右括号')',则将栈顶元素弹出并添加到后缀表达式字符串中,直到栈顶元素是左括号'(',最后将左括号'('出栈。\n4. 遍历完中缀表达式后,将栈中剩余的运算符依次弹出并添加到后缀表达式字符串中。\n\n下面是一个示例代码实现:\n\ncpp\n#include <iostream>\n#include <stack>\n#include <string>\n\nbool isOperator(char c) {\n return c == '+' || c == '-' || c == '*' || c == '/';\n}\n\nint getPriority(char c) {\n if (c == '+' || c == '-') {\n return 1;\n } else if (c == '*' || c == '/') {\n return 2;\n } else {\n return 0;\n }\n}\n\nstd::string infixToPostfix(const std::string& infix) {\n std::stack<char> stk;\n std::string postfix;\n\n for (char c : infix) {\n if (isOperator(c)) {\n while (!stk.empty() && isOperator(stk.top()) && getPriority(stk.top()) >= getPriority(c)) {\n postfix += stk.top();\n stk.pop();\n }\n stk.push(c);\n } else if (c == '(') {\n stk.push(c);\n } else if (c == ')') {\n while (!stk.empty() && stk.top() != '(') {\n postfix += stk.top();\n stk.pop();\n }\n if (!stk.empty()) {\n stk.pop(); // 弹出左括号\n }\n } else {\n postfix += c;\n }\n }\n\n while (!stk.empty()) {\n postfix += stk.top();\n stk.pop();\n }\n\n return postfix;\n}\n\nint main() {\n std::string infix = \"a+b*c-(d+e)/f\";\n std::string postfix = infixToPostfix(infix);\n std::cout << \"Infix expression: \" << infix << std::endl;\n std::cout << \"Postfix expression: \" << postfix << std::endl;\n return 0;\n}\n\n\n运行结果:\n\n\nInfix expression: a+b*c-(d+e)/f\nPostfix expression: abc*+de+f/-\n\n\n这样就完成了中缀表达式到后缀表达式的转换。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pQzM 著作权归作者所有。请勿转载和采集!