#include"stdio.h" char A[7]={'+','-','*','/','(',')','#'}; char B[7][7]={{'>','>','<','<','','>'}, {'>','>','<','<','','>'}, {'>','>','>','>','','>'}, {'>','>','>','>','','>'}, {'<','<','<','<','','>','>','>','0','>','>'}, {'<','<','<','<','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='0'&&c='0'&&c<='9'); } else { switch(precede(gettop1(OPTR),c)) { 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); }
2022-03-07 21:01:18 3KB 堆栈表达式求值
1