⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 堆栈表达式求值.c

📁 堆栈表达式求值系统,处理整型数
💻 C
字号:
#include<stdio.h>
#include<malloc.h>
#define null 0
#define stack_size 100
typedef struct{
    int *base;
    int *top;
    int stacksize;
}stack;
void init(stack *s){
    s->base=(int*)malloc(stack_size*sizeof(int));
    s->top=s->base;
    s->stacksize=stack_size;
}
int gettop(stack *s){
    char e;
    e=*(s->top-1);
    return e;
}
void push(stack *s,int e){
    *s->top++=e;
}
int pop(stack *s){
    int e;
    e=*--s->top;
    return e;
}

int compare(char e){
    char op[7]={'(',')','*','/','-','+','#'};
    int i=0;
    while(op[i]!=e){i++; }
    if(i>6)return 0;
    else return 1;
} //t[i]代入形参,digit转换为字符
int trust(char x){
    int a;
    switch(x){
    case '#': a=0;break;
    case '(': a=1;break;
    case '+': a=2;break;
    case '-': a=2;break;
    case '*': a=3;break;
    case '/': a=3;break;
    case ')': a=4;break;
    }return a;
}
char precede(char a,char b){
    int x,y;
    x=trust(a);
    y=trust(b);
    if(x==0&&y==0)return '=';
    if(x==1&&y==4)return '=';
    else
        if(y==4)return '>';
    else
        if(y==1)return '<';

    else
        if(x>y||x==y) return '>';

    else
        return '<';
    }
int operate(int a,char theta,int b){
    int r;
    switch(theta){
        case '+':r=a+b;break;
        case '-':r=a-b;break;
        case '*':r=a*b;break;
        case '/':r=a/b;break;
    }
    return r;
}
int way(char t[]){
    stack ch,num,f,c;int i=0,x,a,b,l,m,y,theta,k,j;

    init(&ch);push(&ch,'#');
    init(&num);
    while(t[i]){
        j=compare(t[i]);
        if(t[i]>=48&&t[i]<=57){
            x=t[i]-48;i++;
        while(t[i]>=48&&t[i]<=57){x=10*x+t[i]-48;i++;}
            push(&num,x);
        }
        else
            if(j){
            y=t[i];i++;
            k=gettop(&ch);
        good:
                if(y!='#'||k!='#'){
                l=precede(k,y);
                switch(l){
                    case '<':push(&ch,y);break;
                    case '=':pop(&ch);break;
                    case '>':theta=pop(&ch);b=pop(&num);a=pop(&num);
                    x=operate(a,theta,b);push(&num,x); k=gettop(&ch);
        goto good;

                }

            }
        }
        }

    m=gettop(&num);
    printf("Output the result of EvaluateExpression:\n %d\n",m);/*算术表达式结果*/
    }


main(){
    char s1[100],s2[]="exit";
    printf("Please input EvaluateExpression # is the sigal of start EvaluateExpression.\n");
    printf("If you want to end the expression,input # .\n");
    printf("If you want to leave.please input exit\n");
    scanf("%s",s1);
    while(strcmp(s1,s2)){
    way(s1);printf("Please input EvaluateExpression(#is the sigal of ending the EvaluateExpression.\n");
    printf("If you want to leave.please input exit\n");
    scanf("%s",s1);
    }

   }



⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -