题的链接:点击这里!
题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。
输入格式
输入:后缀表达式
输出格式
输出:表达式的值
输入输出样例
输入 #1复制
3.5.2.-*7.+@
输出 #1复制
16
说明/提示
字符串长度,1000内。
题解: 遇到数字将其转化为int型再累加,放入栈中,遇到 . 把ans存入栈中,将ans清零从新开始下一轮计算。遇到其他 + - * / 取出栈顶的两个元素计算后再压入栈。最后输出栈顶;
参考代码1.0: 利用STL的栈stack.
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAX 5010
using namespace std;
int main()
{
char c;
int ans = 0;
stack<int> s;
while((c = getchar()) != '@')
{
if(c >= '0' && c <= '9') ans = ans * 10 + c-'0';
else if(c == '.')
{
s.push(ans);
ans = 0;
}
else
{
int a = s.top(); s.pop();
int b = s.top(); s.pop();
if(c == '+') s.push(b + a);
else if(c == '-') s.push(b - a);
else if(c == '*') s.push(b * a);
else if(c == '/') s.push(b / a);
}
}
cout << s.top() << endl;
return 0;
}
参考代码2.0: 利用数组模拟栈
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
#define MAX 5010
using namespace std;
int s[1010];
int main()
{
char c;
int i = 0;
int ans = 0;
while((c = getchar()) != '@')//3.5.2.-*7.+@
{
if(c >= '0' && c <= '9') ans = ans * 10 + c-'0';
else if(c == '.')
{
s[i++] = ans;
ans = 0;
}
else
{
int a = s[i - 1], b = s[i - 2];
if(c == '+') s[i - 2] = b + a;
else if(c == '-') s[i - 2] = b - a;
else if(c == '*') s[i - 2] = b * a;
else if(c == '/') s[i - 2] = b / a;
i--;
}
}
cout << s[0] << endl;
return 0;
}