#include"stdio.h"
#include"stdlib.h"
#include"string.h"
#include"math.h"
#define MAX 100
#define ADD 10
enum status{ok,fail};
//操作数
typedef struct{
int *base;
int *top;
int stacksize;
}opndstack;
//操作符
typedef struct{
char *base;
char *top;
int stacksize;
}optrstack;
//初始化操作数
enum status Initopndstack(opndstack *S){
(*S).base=(int *)malloc(MAX*sizeof(int));
if(!S->base) return fail;
S->top=S->base;
S->top=0;
S->top++;
S->stacksize=MAX;
return ok;
}
//初始操作符
enum status Initoptrstack(optrstack *S){
(*S).base=(char *)malloc(MAX*sizeof(char));
if(!S->base) return fail;
S->top=S->base;
*(S->base)='#';
S->top++;
S->stacksize=MAX;
return ok;
}
//压入操作数
enum status push1(opndstack *S,int e){
if(S->top-S->base>=MAX) {
S->base=(int *)realloc(S->base,MAX*sizeof(int));
if(!S->base) return fail;
S->top=S->base+S->stacksize;
S->stacksize+=ADD;
}
*(S->top)++=e;
return ok;
}
//取栈顶元素用e返回其值,并删除 操作数
enum status pop1(opndstack *S,int *e){
if(S->base==S->top) return fail;
*e=*--S->top;
return ok;
}
//压入操作符
enum status push2(optrstack *S,char e){
if(S->top-S->base>=MAX) {
S->base=(char *)realloc(S->base,MAX*sizeof(char));
if(!S->base) return fail;
S->top=S->base+S->stacksize;
S->stacksize+=ADD;
}
*S->top++=e;
return ok;
}
//取栈顶元素用e返回其值,并删除 操作符
enum status pop2(optrstack *S,char *e){
if(S->base==S->top) return fail;
*e=*--S->top;
return ok;
}
//取栈顶操作符 不删除
enum status gettop(optrstack S,char *e){
if(S.base==S.top) return fail;
*e=*(S.top-1);
return ok;
}
//操作符优先权的比较
char precede(char e3,char e2){
switch(e3){
case '+':if(e2=='+'||e2=='-'||e2==')') return '>';else return '<';break;
case '-':if(e2=='+'||e2=='-'||e2==')') return '>';else return '<';break;
case '*':return '>';break;
case '/':return '>';break;
case '(':if(e2==')') return '=';else return '<';break;
}
}
//计算函数
int operate(int x1,int x2,char y2){
int k;
switch(y2){
case'+':k=x2+x1;break;
case'-':k=x2-x1;break;
case'*':k=x1*x2;break;
case'/':k=x2/x1;break;
}
return k;
}
void main(){
opndstack S1;optrstack S2;enum status m1,m2;int e1,x1,x2;char e2,e3,y1,y2;
m1=Initopndstack(&S1);
m2=Initoptrstack(&S2);
if(m1==fail||m2==fail) {printf("not succeceful to creat the stack\n"); getchar(); exit(0);}
printf("请输入表达式\n");
e2=getchar();
// if(e2!='='||e2!='+'||e2!='-'||e2!='*'||e2!='/'||e2!='('||e2!')') e2=(int)e2;
while(e2!='='){
scanf("%d",&e1);
push1(&S1,e1);
scanf("%c",&e2);
if(e2=='=') break;
gettop(S2,&e3);
switch(precede(e3,e2)){
case'<':
push2(&S2,e2);break;
case'=':
pop2(&S2,&y1);break;
case'>':
pop2(&S2,&y2);
pop1(&S1,&x1);pop1(&S1,&x2);
push1(&S1,operate(x1,x2,y2));break;
}
}
pop1(&S1,&x2);
printf("%d",x2);
getchar();
}