中缀表达式求值

来源:互联网 发布:少女前线 妖精数据 编辑:程序博客网 时间:2024/05/17 06:33
#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;}
0 0