首页 > 学院 > 开发设计 > 正文

中缀表达式求值

2019-11-10 22:12:51
字体:
来源:转载
供稿:网友
#include<stdio.h>#include<stdlib.h>#include<cstring>using namespace std;char s[100001],c[100001],zhan[100001];int top,lenc,calc[100001];int bj(char a,char b){ if(a=='+') if(b=='+' || b==')' || b=='-' || b=='@')return 1; else return 0; if(a=='-') if(b=='+' || b==')' || b=='-' || b=='@')return 1; else return 0; if(a=='*') if(b=='(')return 0; else return 1; if(a=='/') if(b=='(')return 0; else return 1; if(a=='(') if(b==')')return 2; else return 0; if(a==')') if(b=='(')return 2; else return 0; if(a=='@')return 0;}void zhuanhuan(char s[]){ int i=0; zhan[++top]='@'; while(i<strlen(s)){ if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/') if(s[i-1]=='+' || s[i-1]=='*' || s[i-1]=='-' || s[i-1]=='/'){ PRintf("NO/n");exit(0); } if(s[i]=='@')break; if(s[i-1]>='0' && s[i-1]<='9' &&(s[i]<'0' || s[i]>'9'))c[lenc++]=' '; if(s[i]>='0' && s[i]<='9')c[lenc++]=s[i]; else{ while(bj(zhan[top],s[i])==1 && top>1){ c[lenc++]=zhan[top--]; } if(bj(zhan[top],s[i])==0)zhan[++top]=s[i]; else if(top>1)top--; } i++; } if(top>1)c[lenc++]=' '; printf(""); while(top>1){ c[lenc++]=zhan[top];top--; }}void cmp(){ int i=0; while(i<strlen(c)){ if(c[i]=='+')calc[--top]=calc[top]+calc[top+1]; else if(c[i]=='-')calc[--top]=calc[top]-calc[top+1]; else if(c[i]=='*')calc[--top]=calc[top]*calc[top+1]; else if(c[i]=='/')calc[--top]=calc[top]/calc[top+1]; else{ top++;int x=0; while(c[i]>='0' && c[i]<='9')x=x*10+c[i++]-'0'; calc[top]=x; } i++; }}int main(){ freopen("expr.in","r",stdin); freopen("expr.out","w",stdout); int i,j,k,n,m; gets(s); zhuanhuan(s); top=0; cmp(); printf("%d/n",calc[1]); return 0;}
上一篇:poj1517

下一篇:Yacc介绍与使用

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表