中缀表达式求值

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值