7-2 后缀式求值(一位整型操作数版)
时间: 2023-11-03 12:13:38 浏览: 86
后缀式求值是将表达式中的运算符放在操作数之后,然后依次计算得到最终结果的一种方式。例如,后缀式“5 6 +”表示将5和6相加,结果为11。
下面是一位整型操作数版的后缀式求值的实现:
```c++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int evaluate(string postfix) {
stack<int> s;
for (char c : postfix) {
if (isdigit(c)) {
s.push(c - '0');
} else if (c == '+') {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(a + b);
} else if (c == '-') {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(a - b);
} else if (c == '*') {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(a * b);
} else if (c == '/') {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(a / b);
}
}
return s.top();
}
int main() {
string postfix = "52+3*";
int result = evaluate(postfix);
cout << result << endl; // 输出 21
return 0;
}
```
在这个实现中,我们使用了一个栈来存储操作数。对于后缀式中的每个字符,我们检查它是否是数字。如果是数字,我们将它转换为整数并将其压入栈中。如果是运算符,我们从栈中弹出两个操作数,并根据运算符计算它们的结果,然后将结果压入栈中。最终,栈中仅剩一个元素,即后缀式的结果。