逆波兰式动画演示代码
时间: 2023-12-25 19:27:13 浏览: 94
```C++
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int performOperation(char operation, int operand1, int operand2) {
if (operation == '+') {
return operand1 + operand2;
} else if (operation == '-') {
return operand1 - operand2;
} else if (operation == '*') {
return operand1 * operand2;
} else if (operation == '/') {
return operand1 / operand2;
}
return -1;
}
int evaluatePostfix(string exp) {
stack<int> s;
for (char& c : exp) {
if (isdigit(c)) {
s.push(c - '0');
} else if (isOperator(c)) {
int operand2 = s.top();
s.pop();
int operand1 = s.top();
s.pop();
int result = performOperation(c, operand1, operand2);
s.push(result);
}
}
return s.top();
}
int main() {
string exp = "231*+9-";
cout << "The result of evaluation is: " << evaluatePostfix(exp);
return 0;
}
```
阅读全文