复旦大学2016计算机复试上机——第二题(后缀表达式求值)
题目:给定一个后缀序列,要求求值,只有加减:
水题,后缀直接用栈做就好了,人家复试都是给前缀,要转换的
输入:123++4-
输出:2
#include <string>
#include <iostream>
#include <stack>
using namespace std;
stack<char> op; stack <int>num;
int main()
{
string a;cin>>a;
for(int i=0;i<a.length();i++)
{
if(a[i]>='0' && a[i]<='9')
num.push(a[i]-'0');
else
{
int tempa,tempb; tempa =num.top();num.pop();tempb=num.top();num.pop();
int c;
if(a[i]=='-')
c = tempb-tempa;
else
c = tempb+tempa;
num.push(c);
}
}
printf("%d\n",num.top());
return 0;
}