<span style="font-family: 微软雅黑, 'Trebuchet MS', Helvetica, Arial, Geneva, sans-serif; background-color: rgb(255, 255, 255);">数据结构实验之栈三:后缀式求值</span>
Time Limit: 1000MS Memory limit: 65536K
题目描述
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
输入
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
输出
求该后缀式所对应的算术表达式的值,并输出之。
示例输入
示例输出
提示
基本操作数都是一位正整数!
来源
#include<bits/stdc++.h>
using namespace std;
int main ()
{
char c;
stack<int>s;
int sum=0;
while(cin>>c&&c!='#')
{
if(c>='0'&&c<='9')
s.push(c-'0');
else
{
if(c=='*')
{
sum=s.top();
s.pop();
sum*=s.top();
s.pop();
s.push(sum);
}
else if (c=='/')
{
int v=s.top();
s.pop();
int t=s.top();
sum=t/v;
s.pop();
s.push(sum);
}
else if (c=='+')
{
sum=s.top();
s.top();
sum+=s.top();
s.pop();
s.push(sum);
}
else if (c=='-')
{
int v=s.top();
s.pop();
int t=s.top();
sum=t-v;
s.pop();
s.push(sum);
}
}
}
cout<<sum;
return 0;
}