数据结构实验之栈三:后缀式求值
时间:2022-04-26 21:51
数据结构实验之栈三:后缀式求值
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
stackq;
char str[110];
scanf("%s",str);
for(int i=0;str[i]!='#';i++)
{
if(str[i]>='0'&&str[i]<='9')//这是ASCII码值的大小,要成为正常的大小,要减去48;坑了好久
q.push(str[i]-48);
else//以下就是反复的入栈出栈,相当于把一般式化为后缀式的反向应用。
{
if(str[i]=='+')
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int c=a+b;
q.push(c);
}
if(str[i]=='-')
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int c=b-a;
q.push(c);
}
if(str[i]=='*')
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int c=a*b;
q.push(c);
}
if(str[i]=='/')
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
int c=b/a;
q.push(c);
}
}
}
printf("%d\n",q.top());//最后剩下的这个元素就是最终结果。
return 0;
}