将中缀表达式转化为后缀表达式并输出用switch
时间: 2024-10-13 16:05:54 浏览: 56
将中缀表达式(也称为前缀表达式)转换成后缀表达式(也称为逆波兰表示法,RPN),通常使用了两个栈的数据结构以及递归或迭代的方式。这里是一个简单的例子,使用C++和`switch`来演示这个过程。注意这只是一个简化版的示例,并未包括所有的边界条件和错误处理。
首先,我们需要定义一些基本的运算符优先级,用于`switch`判断:
```cpp
enum Priority {
LEFT_PAREN = 0,
FUNCTION,
ADD_SUB,
MUL_DIV,
EXPONENT,
LOWEST
};
```
然后我们有一个函数`to_postfix(const std::string &infix)`:
```cpp
std::string infixToPostfix(const std::string &infix) {
std::stack<std::pair<char, int>> operators; // 左括号栈
std::stack<char> output; // 后缀表达式堆栈
for (char c : infix) {
switch (c) {
case '(': operators.push({c, LEFT_PAREN});
break;
case ')':
while (!operators.empty() && operators.top().first != '(') {
output.push(operators.top().first);
operators.pop();
}
if (!operators.empty()) operators.pop(); // 只能匹配一个左括号
break;
// 运算符处理
default:
if (isalnum(c)) output.push(c); // 数字直接加入后缀
else {
while (!operators.empty() && operators.top().second >= priority(c)) {
output.push(operators.top().first);
operators.pop();
}
operators.push({c, static_cast<int>(Priority::cToInt(c))});
}
}
}
// 弹空栈中的剩余运算符
while (!operators.empty()) {
output.push(operators.top().first);
operators.pop();
}
return output.str();
}
// 转换后的字符到优先级的映射函数(假设是硬编码)
int priority(char op) {
// ... 定义每个运算符的优先级 ...
}
// 示例中的简单映射,仅做演示
const char* Priority::cToInt(char c) {
switch (c) {
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '^': return 3;
default: return LOWEST;
}
}
```
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)