#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int compare(char ch1,char ch2){
switch(ch1){
case '+':
case '-':if(ch2=='*'||ch2=='/')
return 1;
else
return 0;
break;
case '*':
case '/':return 0;break;
}
}
int main()
{
vector <char>num;
stack <char>ope;
stack <int>cal;
char a;
while(cin>>a&&a!='='){
if(a>='0'&&a<='9'){
num.push_back(a);
}
else{
if(!ope.empty()){
while(!ope.empty()&&compare(a,ope.top())){
num.push_back(ope.top());
ope.pop();
}
ope.push(a);
}
else
ope.push(a);
}
}
while(!ope.empty()){
num.push_back(ope.top());
ope.pop();
}
for(auto ch:num)
cout<<ch<<' ';
cout<<endl;
int sum=0;
for(auto d:num){
if(d>='0'&&d<='9'){
cal.push(d-'0');
}
else{
int a=cal.top();
cal.pop();
int b=cal.top();
cal.pop();
switch(d){
case '+':sum=a+b;
cal.push(sum);break;
case '-':sum=b-a;
cal.push(sum);break;
case '*':sum=a*b;
cal.push(sum);break;
case '/':sum=b/a;
cal.push(sum);break;
}
}
}
cout<<sum<<endl;
return 0;
}
简单的个位后缀表达式实现——栈的应用
最新推荐文章于 2022-08-11 21:45:08 发布