点击获取原题链接
数据结构实验之栈三:后缀式求值
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic Discuss
Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Example Input
59*684/-3*+#
Example Output
57
Hint
基本操作数都是一位正整数!
Author
#include <bits/stdc++.h>
using namespace std;
int main()
{
char c;
stack<int>l;
while(cin>>c && c!='#')///输入字符串
{
if(c=='+')/// 遇到运算符时贪吃栈顶的两个数字进行运算 注意运算方向就可
{
int a=l.top();
l.pop();
int b=l.top();
l.pop();
a+=b;
l.push(a);
}
else if(c=='-')
{
int a=l.top();
l.pop();
int b=l.top();
l.pop();
b-=a;
l.push(b);
}
else if(c=='/')
{
int a=l.top();
l.pop();
int b=l.top();
l.pop();
b/=a;
l.push(b);
}
else if(c=='*')
{
int a=l.top();
l.pop();
int b=l.top();
l.pop();
a*=b;
l.push(a);
}
else
{
int t=c-'0';///将字符转换为以为整形数字
l.push(t);
}
}
cout<<l.top()<<endl;
return 0;
}