表达式运算优先级堆栈

时间:2013-12-03 17:32:01
【文件属性】:
文件名称:表达式运算优先级堆栈
文件大小:3KB
文件格式:TXT
更新时间:2013-12-03 17:32:01
堆栈表达式求值 #include"stdio.h" char A[7]={'+','-','*','/','(',')','#'}; char B[7][7]={{'>','>','<','<','<','>','>'}, {'>','>','<','<','<','>','>'}, {'>','>','>','>','<','>','>'}, {'>','>','>','>','<','>','>'}, {'<','<','<','<','<','=','0'}, {'>','>','>','>','0','>','>'}, {'<','<','<','<','<','0','='}}; typedef struct stack1 { int top; int base; char s[20]; }stack1; typedef struct stack2 { int top; int base; int s[20]; }stack2; void Initstack1(stack1 *S) { S->top=S->base=0; } void Initstack2(stack2 *S) { S->top=S->base=0; } int push1(stack1 *S,char ch) { S->s[S->top]=ch; S->top++; } int push2(stack2 *S,int ch) { S->s[S->top]=ch; S->top++; } int search(char ch) { int i=0; while(ch!=A[i]) { i++; } return i; } char precede(char c1,char c2) { int i,j; i=search(c1); j=search(c2); return B[i][j]; } char gettop1(stack1 S) { char e; if(S.top==S.base) printf("!!!"); e=S.s[S.top-1]; return e; } int gettop2(stack2 S) { int e; if(S.top==S.base) printf("!!!"); e=S.s[S.top-1]; return e; } char pop1(stack1 *S) { if(S->top==S->base) return('!'); else { S->top--; return(S->s[S->top]); } } int pop2(stack2 *S) { if(S->top==S->base) return('!'); else { S->top--; return(S->s[S->top]); } } int operate(int a,char op,int b) { switch(op) { case '+':return(a+b);break; case '-':return(a-b);break; case '*':return(a*b);break; case '/':return(a/b);break; } } int main() { struct stack1 OPTR; struct stack2 OPND; char c,op; int a,b,an; Initstack1(&OPTR); push1(&OPTR,'#'); Initstack2(&OPND); c=getchar(); while(c!='#'||gettop1(OPTR)!='#') { if(c>='0'&&c<='9') { push2(&OPND,c-'0'); c=getchar(); do { if(c>='0'&&c<='9') push2(&OPND,pop2(&OPND)*10+(c-'0')); }while(c>='0'&&c<='9'); } else { switch(precede(gettop1(OPTR),c)) { case '<': push1(&OPTR,c);c=getchar();break; case '=': c=pop1(&OPTR);c=getchar();break; case '>': op=pop1(&OPTR);a=pop2(&OPND);b=pop2(&OPND); push2(&OPND,operate(b,op,a));break; }//switch } //else } //while an=pop2(&OPND); printf("\nyour answer is:\n=%d",an); }

网友评论