/*测试数据范围:
0~2147483647
结果数据范围-2147483648~2147483647*/
#include
#include
#define MAXSIZE 20 //栈的最大值
typedef char ElemType; //定义字符栈
typedef struct {
ElemType base2[MAXSIZE];
int top2;
}Stack2;
typedef int SElemType; //定义整形栈
typedef struct {
SElemType base1[MAXSIZE];
int top1;
}Stack1;
//初始化
void InitStack2(Stack2 &S){
S.top2=0;
}
void InitStack1(Stack1 &S){
S.top1=0;
}
int StackFull2(Stack2 S){
return S.top2==MAXSIZE;
}
int StackFull1(Stack1 S){
return S.top1==MAXSIZE;
}
//压栈
void Push2 (Stack2 &S,ElemType e){
if(!StackFull2(S)) S.base2[S.top2++]=e;
else printf("Full!") ;
}
void Push1 (Stack1 &S,SElemType e){
if(!StackFull1(S)) S.base1[S.top1++]=e;
else printf("Full!") ;
}
int StackEmpty2(Stack2 S){
return S.top2==0;
}
int StackEmpty1(Stack1 S){
return S.top1==0;
}
//弹栈
void Pop2(Stack2 &S,ElemType &e){
if(!StackEmpty2(S)) e=S.base2[--S.top2];
else printf("Empty!");
}
void Pop1(Stack1 &S,SElemType &e){
if(!StackEmpty1(S)) e=S.base1[--S.top1];
else printf("Empty!");
}
//取当前字符
char Gettop2(Stack2 &S ,ElemType &x){
if(!StackEmpty2(S)){x=S.base2[S.top2-1];
return x;}
else exit(-1);
}
int Gettop1(Stack1 &S ,SElemType &x){
if(!StackEmpty1(S)){x=S.base1[S.top1-1];
return x;}
else exit(-1);
}
//判断优先级
int Precede(char m,char n){
int a[7][7]={
{1,1,2,2,2,1,1},
{1,1,2,2,2,1,1},
{1,1,1,1,2,1,1},
{1,1,1,1,2,1,1},
{2,2,2,2,2,3,0},
{1,1,1,1,0,1,1},
{2,2,2,2,2,0,3}
};
int x=0;int y=0;
int i=0;
char b[7]={'+','-','*','/','(',')','#'};
while(m!=b[i]){i++;x++;} ;
i=0;
while(n!=b[i]){i++;y++;} ;
return a[x][y];
}
//进行四则运算
int Operate(int m,char theta,int n){
if (theta=='+')return(m+n);
else if (theta=='-')return(n-m);
else if (theta=='*')return(m*n);
else if (theta=='/') return(n/m);
else exit(-1);
}
//求表达式的值
int EvaluateExpression(){
char x,theta,ch,c2;
int m,n,c1,ch1,flag=0,sflag;//设标志符号flag用来判断循环
Stack2 S2;
Stack1 S1;
InitStack2(S2); Push2(S2,'#');
InitStack1(S1);ch=getchar();
while ((ch!='#'||Gettop2(S2,c2)!='#')&&flag==0){
if('0'<=ch&&ch<='9'){
ch1=ch-'0';//解决0-9的限制
sflag=0;
while(sflag==0){
ch=getchar();
if('0'<=ch&&ch<='9' )ch1=ch1*10+(ch-'0');
else{sflag=1;
Push1(S1,ch1);
}
}
}
else
switch(Precede(Gettop2(S2,c2),ch)){
case 2:
Push2(S2,ch);ch=getchar();
break;
case 3:
Pop2(S2,x);ch=getchar();
break;
case 1:
Pop2(S2,theta);
Pop1(S1,m);
Pop1(S1,n);
Push1(S1,Operate(m,theta,n));
break;
default:
printf("The expression has something wrong!");
flag=1;
break;
}
}if (flag==0) return Gettop1(S1,c1);
else {printf("\n");
exit(-1);
}
}
//主程序
void main(){
int g;
printf(" 测试数据范围:0~2147483647\n");
printf("结果数据范围-2147483648~2147483647\n");
printf("Input expression,and end of '#':\n");
g=EvaluateExpression();
printf("%5d\n",g);
}
--------------------next---------------------
阅读(1063) | 评论(0) | 转发(0) |