#include "iostream.h" #include "stdio.h" #define MAX 20 typedef struct //定义操作数的栈 { int data[MAX]; int top; }AB;
typedef struct //定义操作符的栈 { char ch[MAX]; int top; }CD;
AB* InitStack1(); CD* InitStack2(); int Empty1(AB *r); int Empty2(CD *s); void Push1(AB *r,int a); void Push2(CD *s,char b); int Full1(AB *r); int Full2(CD *s); void Pop1(AB *r,int m); //出栈并返回栈顶元素m void Pop2(CD *s,char n); //出栈并返回栈顶元素n int GetTop1(AB *r); char GetTop2(CD *s); int precede(char c1,char c2); //比较运算符的优先级 int operate(int x,char y,int z); //进行x,z关于y的运算
void main() { AB *p; CD *q; char c,e; int a,b; p=InitStack1(); q=InitStack2(); Push2(q,'#'); c=getchar(); while(c!='#'&&GetTop2(q)!='#') { if(c<='9'&&c>='0') { Push1(p,c); c=getchar(); } else { switch(precede(GetTop2(q),c)) { case -1 : Push2(q,c); c=getchar(); break; case 0 : Pop2(q,e); c=getchar(); break; case 1 : Pop2(q,e); Pop1(p,a); Pop1(p,b); Push1(p,operate(a,e,b)); break; default : break; } } } return GetTop1(p); }
AB* InitStack1() //初始化栈 { AB *p; p=new AB; p->top=0; }
CD* InitStack2() //初始化栈 { CD *q; q=new CD; q->top=0; }
int Empty1(AB *r) { return r->top=0; }
int Empty2(CD *s) { return s->top=0; }
void Push1(AB *r,int a) { if(Full1(r)) cout<<"The stack is full.\n"; else r->data[r->top++]=a; }
void Push2(CD *s,char b) { if(Full2(s)) cout<<"The stack is full.\n"; else s->ch[s->top++]=b; }
int Full1(AB *r) { return r->top=MAX-1; }
int Full2(CD *s) { return s->top=MAX-1; }
void Pop1(AB *r,int m) //出栈并返回栈顶元素m { if(Empty1(r)) cout<<"The stack is empty.\n"; else { m=r->data[r->top]; r->top--; } }
void Pop2(CD *s,char n) //出栈并返回栈顶元素n { if(Empty2(s)) cout<<"The stack is empty.\n"; else { n=s->ch[s->top]; s->top--; } }
int GetTop1(AB *r) { return r->data[r->top-1]; }
char GetTop2(CD *s) { return s->ch[s->top-1]; }
int precede(char c1,char c2) { if((c1=='+')&&(c2=='+'||c2=='-'||c2==')'||c2=='#')) return 1; if((c1=='+')&&(c2=='*'||c2=='/'||c2=='(')) return -1; if((c1=='-')&&(c2=='+'||c2=='-'||c2==')'||c2=='#')) return 1; if((c1=='-')&&(c2=='*'||c2=='/'||c2=='(')) return -1; if((c1=='*')&&(c2=='+'||c2=='-'||c2=='/'||c2==')'||c2=='#')) return 1; if((c1=='*')&&(c2=='*'||c2=='/')) return 1; if((c1=='*'||c1=='/')&&c2=='(') return -1; if((c1=='*'||c1=='/')&&(c2==')'||c2=='#')) return 1; if(c1=='('&&(c2=='+'||c2=='-'||c2=='*'||c2=='/')) return -1; if(c1=='('&&c2==')') return 0; if(c1==')'&&(c2=='+'||c2=='-'||c2=='*'||c2=='/')) return 1; if(c1==')'&&(c2==')'&&c2=='#')) return 1; if(c1=='#'&&(c2=='+'||c2=='-')) return -1; if(c1=='#'&&(c2=='*'||c2=='/')) return -1; if(c1=='#'&&c2==')') return -1; if(c1=='#'&&c2=='#') return 0; }
int operate(int x,char y,int z) { int dd; switch(y) { case '+' : dd=x+z; break; case '-' : dd=x-z; break; case '*' : dd=x*z; break; case '/' : dd=x/z; break; default : break; } return dd; } ////////////////////////////////////////////////////////////////////////////// 以上是我写的程序,但是运行不起来,而且有错。鄙人是一个菜鸟,希望高手们给我教导,谢谢