中缀表达式转后缀表达式 c++完整代码
时间: 2024-06-26 12:01:41 浏览: 6
中缀表达式转后缀表达式(也称为逆波兰表示法或前缀表示法)的过程通常使用栈来辅助完成。下面是用C++实现的一个简单版本:
```cpp
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
bool isOperator(char op) {
return op == '+' || op == '-' || op == '*' || op == '/';
}
std::string infixToPostfix(const std::string &expr) {
std::stack<char> ops;
std::string postfix;
for (char ch : expr) {
if (isdigit(ch)) {
postfix += ch;
} else if (isOperator(ch)) {
while (!ops.empty() && isOperator(ops.top()) && precedence(ch) <= precedence(ops.top())) {
postfix += ops.top();
ops.pop();
}
ops.push(ch);
} else if (ch == '(') {
ops.push(ch);
} else if (ch == ')') {
while (!ops.empty() && ops.top() != '(') {
postfix += ops.top();
ops.pop();
}
if (ops.top() != '(') {
throw std::runtime_error("Invalid expression");
}
ops.pop();
}
}
while (!ops.empty()) {
postfix += ops.top();
ops.pop();
}
return postfix;
}
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return -1; // For operators with no precedence, assume it's lower than any
}
int main() {
std::string infixExpr = "A+B*C";
std::string postfixExpr = infixToPostfix(infixExpr);
std::cout << "Infix expression: " << infixExpr << "\n";
std::cout << "Postfix expression: " << postfixExpr << "\n";
return 0;
}
```
在这个代码中,我们定义了一个`infixToPostfix`函数,它遍历输入的中缀表达式,根据运算符的优先级和括号来决定何时压入栈和何时弹出栈。`precedence`函数用于确定运算符的优先级。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)