#include<stdio.h> #include<stdlib.h> struct elem_N { float data; elem_N *next; }; struct elem_T { char data; elem_T *next; }; struct stack_N { elem_N *top; int length; }; struct stack_T { elem_T *top; int length; }; void Init_stack_N(stack_N *S) { S->top=NULL; S->length=0; } void Init_stack_T(stack_T *S) { S->top=NULL; S->length=0; } void Push_N(stack_N *S,float e) { elem_N *p; p=new elem_N; if(!p)exit(0); p->data=e; p->next=S->top; S->top=p; S->length++; } void Push_T(stack_T *S,char e) { elem_T *p; p=new elem_T; if(!p)exit(0); p->data=e; p->next=S->top; S->top=p; S->length++; } float Pop_N(stack_N *S) { elem_N *p; if(S->top==NULL) return -1; float e; p=S->top; e=p->data; S->top=p->next; S->length--; delete p; return e; } char Pop_T(stack_T *S) { elem_T *p; if(S->top==NULL) return -1; char e; p=S->top; e=p->data; S->top=p->next; S->length--; delete p; return e; } float Operate(float a,char c,float b){ float s; switch(c) { case '+':s=a+b; break; case '-':s=a-b; break; case '*':s=a*b; break; case '/':if(b!=0) s=a/b; else printf("error!/n");break; default:printf("error!/n"); } return s; } float Get_top_N(stack_N *S) { if(S->top==NULL) return -1; float e; e=S->top->data; return e; } char Get_top_T(stack_T *S) { if(S->top==NULL) return -1; char e; e=S->top->data; return e; } int In(char c) { if(c!='+'&&c!='-'&&c!='*'&&c!='/'&&c!='('&&c!=')'&&c!='#') return 1; else return 0; } char Precede(char a,char b) { int p=0,q=0; char m[8]="+-*/()#"; char n[8][8]={">><<<>>",">><<<>>",">>>><>>",">>>><>>","<<<<<= ",">>>> >>","<<<< ="}; while(m[p]!=a)p++; while(m[q]!=b)q++; return(n[p][q]); } int main(void) { char c,x,theta; float a,b,e; int i; stack_T OPTR; stack_N OPND; Init_stack_T(&OPTR); Push_T(&OPTR,'#'); Init_stack_N(&OPND); printf("请输入表达式并以#结束):/n例如: 3*(9+5)/5#/n"); c=getchar(); while(c!='#'||Get_top_T(&OPTR)!='#') { if(In(c)) { e=c-'0'; Push_N(&OPND,e); c=getchar(); } else { switch(Precede(Get_top_T(&OPTR),c)) { case'<':Push_T(&OPTR,c);c=getchar();break; case'=':x=Pop_T(&OPTR);c=getchar();break; case'>':theta=Pop_T(&OPTR);b=Pop_N(&OPND);a=Pop_N(&OPND); Push_N(&OPND,Operate(a,theta,b));break; } } } printf("%d",Get_top_N(&OPND)); return 0; } 实验结果截图: