Write+a+program+to+evaluate+a+postfix+expression.+You+only+have+to+handle+four+kinds+of+operators:++
时间: 2023-11-09 22:08:23 浏览: 53
Sure! To evaluate a postfix expression, we can use a stack to keep track of the operands. Here's an example program in C++:
```
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int evaluatePostfix(string exp) {
stack<int> s;
for (int i = 0; i < exp.length(); i++) {
if (isdigit(exp[i])) {
s.push(exp[i] - '0');
} else {
int op2 = s.top();
s.pop();
int op1 = s.top();
s.pop();
switch (exp[i]) {
case '+':
s.push(op1 + op2);
break;
case '-':
s.push(op1 - op2);
break;
case '*':
s.push(op1 * op2);
break;
case '/':
s.push(op1 / op2);
break;
}
}
}
return s.top();
}
int main() {
string exp = "23+4*";
cout << evaluatePostfix(exp) << endl; // Output: 14
return 0;
}
```
In this program, we iterate through the postfix expression character by character. If the character is a digit, we push it onto the stack. If it's an operator, we pop the top two operands from the stack, perform the operation, and push the result back onto the stack. Finally, we return the top element of the stack, which is the result of the expression.