栈实现表达式求值
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+10;
char s[N];
bool flag=0;
char p[N];
int ptt=0;
int num[N],ntt=0;
char Op[N];
int optt=0;
map<char,int>F;
bool check(char c){
return c=='('||c==')'||c>='0'&&c<='9';
}
int getres(char op,int a,int b){
if(op=='+') return a+b;
if(op=='-') return a-b;
if(op=='*') return a*b;
if(op=='/') return a/b;
}
int main(){
F['(']=-1,F[')']=4;
F['+']=0,F['-']=1,F['*']=2,F['/']=3;
cin>>s;
for(int i=0;s[i];i++){
if(s[i]=='('||s[i]==')')
if(!(s[i]==')'&&p[ptt]=='(')) p[++ptt]=s[i];
else ptt--;
if(!check(s[i])&&(i==0||!check(s[i-1]))) flag=1;
}
if(ptt){
cout<<"ERROR:缺少括号";
return 0;
}
if(flag){
cout<<"ERROR:表达式缺操作数";
return 0;
}
int k=0;
for(int i=0;s[i];i++){
if(s[i]>='0'&&s[i]<='9'){
int sum=0;
while(s[i]>='0'&&s[i]<='9') sum=sum*10+s[i]-'0',i++;
i--;
num[++ntt]=sum;
cout<<sum;
}
else if(s[i]=='(') Op[++optt]=s[i];
else if(s[i]==')'){
while(Op[optt]!='('){
char c=Op[optt--];
int b=num[ntt--];
int a=num[ntt--];
num[++ntt]=getres(c,a,b);
//cout<<"\n**"<<num[ntt]<<endl;
if(c!='(')
cout<<c;
}
optt--;
}
else{
if(optt==0||F[Op[optt]]<F[s[i]]) Op[++optt]=s[i];
else {
while(optt>0&&F[Op[optt]]>=F[s[i]]){
char c=Op[optt--];
int b=num[ntt--];
int a=num[ntt--];
num[++ntt]=getres(c,a,b);
//cout<<"\n::"<<num[ntt]<<endl;
cout<<c;
}
Op[++optt]=s[i];
}
}
/*cout<<"-----"<<endl;
for(int j=1;j<=ntt;j++) cout<<num[j];
cout<<endl;
for(int j=1;j<=optt;j++) cout<<Op[j];
cout<<endl;*/
}
while(optt>0){
char c=Op[optt--];
int b=num[ntt--];
int a=num[ntt--];
num[++ntt]=getres(c,a,b);
cout<<c;
}
cout<<endl<<num[ntt];
}