## Stack实现表达式的求值

1.用栈求中缀表达式的值：

int getPriority(char a){
if(a == '+' || a=='-'){
return 0;
}else{
return 1;
}
}
int calSub(float opand1,char op,float opand2,float &result){
if(op == '+')     result =opand1+opand2;
if(op == '-')    result =opand1-opand2;
if(op == '*')    result=opand1*opand2;
if(op == '/'){
if(fabs(opand2)<MIN){
return 0;
}else{
result=opand1/opand2;
}
}
return 1;
}
int calStackTopTwo(float s1[],int &top1,char s2[],int &top2){
float opand1,opand2,result;
char op;
int flag;
opand2=s1[top1--];
opand1=s1[top1--];
op=s2[top2--];
flag=calSub(opand1,op,opand2,result);
if(flag == 0){
cout<<"ERROR"<<endl;
return 0;
}
s1[++top1]=result;
return flag;
}
float calInfix(char exp[]){
float s1[MaxSize]; int top1=-1;
char s2[MaxSize]; int top2=-1;
int i=0;
while(exp[i]!='\0'){
if('0'<=exp[i] && exp[i]<='9'){
s1[++top1]=exp[i]-'0';
++i;
}else if(exp[i] == '('){
s2[++top2]='(';
++i;
}else if(exp[i] == '+'||exp[i] =='-'||exp[i]=='*'||exp[i]=='/'){
if(top2 == -1 ||s2[top2] =='('||getPriority(exp[i])>getPriority(s2[top2])){
s2[++top2]=exp[i];
++i;
}else{
int flag=calStackTopTwo(s1,top1,s2,top2);
if(flag == 0){
return 0;
}
}
}else if(exp[i] ==')'){
while(s2[top2] !='('){
int flag=calStackTopTwo(s1,top1,s2,top2);
if(flag == 0){
return 0;
}
}
--top2;//左括号丢掉
++i;
}
}
while(top2!=-1){
int flag=calStackTopTwo(s1,top1,s2,top2);
if(flag == 0){
return 0;
}
}
return s1[top1];
}

2.用Stack求后缀表达式的值

int calSub(float opand1,char op,float opand2,float &result){
if(op == '+')     result =opand1+opand2;
if(op == '-')    result =opand1-opand2;
if(op == '*')    result=opand1*opand2;
if(op == '/'){
if(fabs(opand2)<MIN){
return 0;
}else{
result=opand1/opand2;
}
}
return 1;
}
float calPostFix(char exp[]){
float s[MaxSize];int top=-1;for(int i=0;exp[i]!='\0';++i){
if('0'<=exp[i] &&exp[i]<=9){
s[++top]=exp[i]-'0';
}else{
float opnd1,opnd2,result;
char op;
int flag;
opnd2=s[top--];
opnd1=s[top--];
op=exp[i];
flag=calSub(opnd1,op,opnd2,result);
if(flag == 0){
cout<<"ERROR"<<endl;
}
s[++top]=result;
}
}
return s[top];
}

3.用Stack求前缀表达式的值

float calPreFix(char exp[],int len){
float s[MaxSize];int top=-1;
int i=len-1;
for(i;i>=0;i--){
if('0'<=exp[i] &&exp[i]<=9){
s[++top]=exp[i]-'0';
}else{
float opnd1,opnd2,result;
char op;
int flag;
opnd2=s[top--];
opnd1=s[top--];
op=exp[i];
flag=calSub(opnd2,op,opnd1,result);
if(flag == 0){
cout<<"ERROR"<<endl;
}
s[++top]=result;
}
}
return s[top];
}

posted on 2020-06-24 15:18  二进制dd  阅读(212)  评论(0编辑  收藏  举报