后缀表达式求值
内存限制: 128 MiB 时间限制: 1000 ms 标准输入输出 题目类型: 传统 评测方式: 文本比较
题目描述
不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行,不再考虑运算符的优先规则,如:(2 + 1) * 3 , 即2 1 + 3 *。这样的表达式称为后缀表达式,也叫逆波兰表达式。它是为了方便在计算机中进行表达式求值而出现的。
给出一个仅由整数 、+、-、*、/等组成的后缀表达式,符号之间用空格分开,计算它的值。/ 表示整除。
输入格式
第1行:1个字符串,即后缀表达式
输出格式
第1行:1个整数,表示运算结果。
样例
样例输入
复制2 1 + 3 *
样例输出
复制9
数据范围与提示
数据保证每个整型数字绝对值不超过100,运算过程中不会超过int,数字总数不超过100个
提示:字符数组转int可以用atoi()函数,需要打开cstdlib头文件
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
int size, top;
int a[maxn];
char s[maxn];
void init() {
size = maxn;
top = 0;
}
bool empty() {
return top == 0;
}
bool full() {
return top == size;
}
void push(int x) {
a[top++] = x;
}
void pop() {
top--;
}
int TOP() {
return a[top - 1];
}
int main() {
init();
while(scanf("%s", s) != EOF) {
int x, y;
if(s[0] >= '0' && s[0] <= '9' || (s[0] == '-' && strlen(s) != 1)) {
x = atoi(s);
push(x);
} else {
x = TOP(), pop();
y = TOP(), pop();
if(s[0] == '+') {
push(x + y);
} else if(s[0] == '-') {
push(y - x);
} else if(s[0] == '*') {
push(x * y);
} else {
push(y / x);
}
}
}
cout << TOP();
return 0;
}
这篇是手打栈,用STL模板的在下面:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
char s[maxn];
stack<int> a;
int main() {
while(a.empty() == false) {
a.pop();
}
while(scanf("%s", s) != EOF) {
int x, y;
if(s[0] >= '0' && s[0] <= '9' || (s[0] == '-' && strlen(s) != 1)) {
x = atoi(s);
a.push(x);
} else {
x = a.top(), a.pop();
y = a.top(), a.pop();
if(s[0] == '+') {
a.push(x + y);
} else if(s[0] == '-') {
a.push(y - x);
} else if(s[0] == '*') {
a.push(x * y);
} else {
a.push(y / x);
}
}
}
cout << a.top();
return 0;
}