1043: 利用栈完成后缀表达式的计算
题目链接-1043: 利用栈完成后缀表达式的计算
解题思路
STL stack
- 从左到右扫描后缀表达式,如果遇到一个操作数,将其压入栈
- 如果遇到一个操作符,则从栈中弹出两个操作数,计算结果,然后把结果入栈
- 直到遍历完后缀表达式,则计算完成,此时的栈顶元素即为后缀表达式的值
- 具体操作见代码
附上代码
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
using namespace std;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+5;
typedef long long ll;
typedef pair<int,int> PII;
stack<int> st;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
char c;
while(cin>>c){
if(c=='#')
break;
if(isdigit(c))//判断是否为数字
st.push(c-'0');
else{
if(c==' ')
continue;
if(c=='+'){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
int num=a+b;
st.push(num);
}
if(c=='-'){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
int num=b-a;
st.push(num);
}
if(c=='*'){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
int num=a*b;
st.push(num);
}
if(c=='/'){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
int num=b/a;
st.push(num);
}
}
}
cout<<st.top();
return 0;
}