#includeusing namespace std; #define MAXSIZE 100 typedef struct { char *base; char *top; int size; }Stack; typedef struct { int *base; int *top; int size; }Stack1; bool creatStack(Stack &S) { S.base=new char[MAXSIZE]; if(!S.base) return false; S.top=S.base; S.size=MAXSIZE; return true; } bool creatStack1(Stack1 &S) { S.base=new int[MAXSIZE]; if(!S.base) return false; S.top=S.base; S.size=MAXSIZE; return true; } bool Push(Stack &S,char e) { if(S.top-S.base==S.size) return false; *S.top=e; S.top++; return true; } bool Push1(Stack1 &S,int e) { if(S.top-S.base==S.size) return false; *S.top=e; S.top++; return true; } bool Pop(Stack &S,char &e) { if(S.top==S.base) return false; S.top--; e=*S.top; return true; } bool Pop1(Stack1 &S,int &e) { if(S.top==S.base) return false; S.top--; e=*S.top; return true; } char Gettop(Stack S) { return *(S.top-1); } int Gettop1(Stack1 S) { return *(S.top-1); } int In(char c) { if(c=='+'||c=='-'||c=='*'||c=='/'||c=='#'||c=='('||c==')') return 1; else return 0; } char Precede(char a,char b) { if(a=='+'||a=='-'){ if(b=='+'||b=='-'||b=='#'||b==')') return '>'; if(b=='*'||b=='/'||b=='(') return '<'; } if(a=='*'||a=='/'){ if(b=='(') return '<'; if(b=='+'||b=='-'||b=='#'||b==')'||b=='*'||b=='/') return '>'; } if(a=='('){ if(b==')') return '='; if(b=='+'||b=='-'||b=='('||b=='*'||b=='/') return '<'; } if(a=='#'){ if(b!='(') { if(b=='#') return '='; else return '<'; } } } int Operate(int a,char x,int b) { switch(x) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } } int evaluate() { Stack OPTR; Stack1 OPND; char ch,x; int a,b; cout<<"创建运算符栈OPTR."< >ch; while(ch!='#'||Gettop(OPTR)!='#') { if(!In(ch)) { Push1(OPND,ch-'0'); cin>>ch; } else { switch(Precede(Gettop(OPTR),ch)) { case '<': Push(OPTR,ch); cin>>ch; break; case '>': Pop(OPTR,x); Pop1(OPND, b); Pop1(OPND, a); Push1(OPND, Operate(a,x,b)); break; case '=': Pop(OPTR,x); cin>>ch; break; } } } return Gettop1(OPND); } int main() { cout<<"表达式最后的结果为:"< 定义了两个结构体,一个用于表示符号型,一个用于表示数字型。creatStack和creatStack1等其他的相关类似的函数目的相同,一个用于操作符号,一个用于操作数值。博主也是刚刚开始学习,所以编译的此代码只能执行10以内的数字,十位数之外的我们一起思考一下吧!



