7-5 逆波兰表达式求值
分数 8
作者 李廷元
单位 中国民用航空飞行学院
逆波兰表示法是一种将运算符(operator)写在操作数(operand)后面的描述程序(算式)的方法。举个例子,我们平常用中缀表示法描述的算式(1 + 2)*(5 + 4),改为逆波兰表示法之后则是1 2 + 5 4 + *。相较于中缀表示法,逆波兰表示法的优势在于不需要括号。
请输出以逆波兰表示法输入的算式的计算结果。
输入格式:
在一行中输入1个算式。相邻的符号(操作数或运算符)用1个空格隔开。
输出格式:
在一行中输出计算结果。
限制:
2≤算式中操作数的总数≤100
1≤算式中运算符的总数≤99
运算符仅包括“+”、“-”、“*”,操作数、计算过程中的值以及最终的计算结果均在int范围内。
输入样例1:
4 3 + 2 -
输出样例1:
5
输入样例2:
1 2 + 3 4 - *
输出样例2:
-3
```c++
#include <iostream>
#include <stdio.h>
using namespace std;
typedef struct
{
int *top;
int *base;
}Stack;
void init ( Stack &S )
{
S.base = new int[1000];
S.top = S.base;
}
void push ( Stack &S, int x )
{
*S.top++ = x;
}
int pop ( Stack &S )
{
int x;
x = * --S.top;
return x;
}
int main ()
{
Stack S;
init (S);
char c;
int num = 0;
while ( scanf ("%c ", &c) != EOF )
{
int x;
if ( c == '+' || c == '-' || c == '*' )
{
num = 0;
int x1, x2;
x1 = pop (S);
x2 = pop (S);
if ( c == '+' )
{
num = x1 + x2;
}
if ( c == '-' )
{
num = x2 - x1;
}
if ( c == '*' )
{
num = x1 * x2;
}
push (S, num);
}
else
{
x = c - '0';
push (S, x);
}
}
cout << num;
return 0;
}
```
调试好的代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string s;
stack<int> nums;
int num = 0;
getline(cin, s);
for (char c : s) {
if (isdigit(c)) {
num = num * 10 + (c - '0');
} else if (c == ' ') {
if (num != 0) {
nums.push(num);
num = 0;
}
} else {
int a = nums.top();
nums.pop();
int b = nums.top();
nums.pop();
int res = 0;
if (c == '+') {
res = b + a;
} else if (c == '-') {
res = b - a;
} else if (c == '*') {
res = b * a;
}
nums.push(res);
}
}
cout << nums.top() << endl;
return 0;
}
+ - *
之间 应该是 if , else if else if 不能是 if if if