第三周——后缀表达式

发布时间 2023-04-15 14:38:04作者: 小白船、

题目描述

所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

如:3*(5-2)+73*(5-2)+7 对应的后缀表达式为:3.5.2.-*7.+@3.5.2.-*7.+@。在该式中,@ 为表达式的结束符号。. 为操作数的结束符号。

输入格式

输入一行一个字符串 s,表示后缀表达式。

输出格式

输出一个整数,表示表达式的值。

输入输出样例

输入 
3.5.2.-*7.+@
输出 
16

题目分析:

本题输入的是后缀表达式

后缀表达式的特点是——不用考虑运算符的优先级

遇到运算符就运算

所以,我们很容易就想到了算法——栈

算法分析:

栈特点——先进后出

本题可以使用栈来解决

遇到数字就入栈

遇到符号就出栈、并运算

再把运算后的结果入栈

 

代码:

#include<iostream>
#include<stack>
using namespace std;
int main()
{
char t;
stack<int> s;
while(cin>>t&&t!='@')//判断是否结束
{
if(t>='0'&&t<='9')
{
int temp=t-'0';//保存数字
while(cin>>t&&t>='0'&&t<='9')
temp=temp*10+t-'0';//保存数字,是否为多位数字
s.push(temp);//放入栈中
}
if(t=='+')//判断加法
{
int a=s.top();//取出第一位
s.pop();//删除第一位
int b=s.top();//b就变成了第一位
s.pop();删除
s.push(b+a);将结果放入栈中,继续计算
}
if(t=='-')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b-a);
}
if(t=='/')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b/a);
}
if(t=='*')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b*a);
}
}
cout<<s.top()<<endl;//输出
return 0;
}