#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
#define dx 105
#define zl 10
char Prior[7][7] = // 运算符优先级表
{
'>','>','<','<','<','>','>',
'>','>','<','<','<','>','>',
'>','>','>','>','<','>','>',
'>','>','>','>','<','>','>',
'<','<','<','<','<','=',' ',
'>','>','>','>',' ','>','>',
'<','<','<','<','<',' ','='
};
typedef struct //构造栈运算符栈
{
char *base;
char *top;
int stacksize;
}fqstack;
int finitqstack(fqstack *s) //初始化运算符栈
{
s->base=(char*)malloc(dx*sizeof(char));
if(!s->base) return -2;
s->top=s->base;
s->stacksize=dx;
return 1;
}
typedef struct //构造栈运算数栈
{
double *base;
double *top;
int stacksize;
}sqstack;
int sinitqstack(sqstack *s) //初始化运算数栈
{
s->base=(double*)malloc(dx*sizeof(double));
if(!s->base) return -2;
s->top=s->base;
s->stacksize=dx;
return 1;
}
int fpush(fqstack *s,char e) //运算符栈入栈
{
if(s->top-s->base>=dx)
{
s->base=(char*)realloc(s->base,(dx+zl)*sizeof(char));
if(!s->base) return -2;
s->top=s->base+s->stacksize;
s->stacksize+=zl;
}
*s->top++=e;
return 1;
}
int spush(sqstack *s,double e) //运算数栈入栈
{
if(s->top-s->base>=dx)
{
s->base=(double*)realloc(s->base,(dx+zl)*sizeof(double));
if(!s->base) return -2;
s->top=s->base+s->stacksize;
s->stacksize+=zl;
}
*s->top++=e;
return 1;
}
char ftop(fqstack *s) //运算符访问栈顶
{
if(s->base==s->top) return -2;
return *(s->top-1);
}
double stop(sqstack *s) //运算数访问栈顶
{
if(s->base==s->top) return -2;
return *(s->top-1);
}
int fpop(fqstack *s,char *x) //运算符弹栈
{
if(s->base==s->top) return -2;
*x=*--s->top;
return 1;
}
int spop(sqstack *s,double *x) //运算数弹栈
{
if(s->base==s->top) return -2;
*x=*--s->top;
return 1;
}
double Operate(double a, char theta, double b) //计算
{
switch(theta)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
default : return 0;
}
}
int is_lx(char c) //判断是运算符还是运算数
{
if(c>='0'&&c<='9') return 1;
return 0;
}
char is_yxj(char c1,char c2) //取下标数组并比较优先级
{
string ss="+-*/()#";
return Prior[ss.find(c1)][ss.find(c2)];
}
int main()
{
fqstack optr;
sqstack opnd;
finitqstack(&optr);
fpush(&optr,'#');
sinitqstack(&opnd);
char c,x,theta;
double a,b;
c=getchar();
while(c!='#'||ftop(&optr)!='#')
{
if(is_lx(c))
{
int xx=0;
while(is_lx(c))
{
xx=xx*10+(c-'0');
c=getchar();
}
spush(&opnd,xx);
}
else
{
switch(is_yxj(ftop(&optr),c))
{
case '<':
fpush(&optr,c);
c=getchar();
break;
case '=':
fpop(&optr,&x);
c=getchar();
break;
case '>':
fpop(&optr,&theta);
spop(&opnd,&b);
spop(&opnd,&a);
spush(&opnd,Operate(a,theta,b));
break;
}
}
}
printf("%.2lf\n",stop(&opnd));
return 0;
}
数据结构_表达式求值
最新推荐文章于 2023-04-24 20:45:04 发布