If I remember correctly, you can solve this problem with two stacks, one for operators, the other for operands.
// OPTR stack: store operators // OPND stack: store operands // OP: predefined set of operators OperandType EvaluateExpression(){ InitStack(OPET);Push(OPTR,'#'); initStack(OPND);c=getchar(); while(c!='#'||GetTop(OPTR)!='#'){ if(!In(c,OP)){Push((OPND,c);c=getchar();} //Push to stack if not operator else switch(Precede(GetTop(OPTR),c){ //Top element in stack has a lower priority case '<': Push(OPTR,c); c=getch(); break; case '=': Pop(OPTR,x); c=getch(); break; //Pop top element and push back the calculated result case '>': Pop(OPTR,theta); Pop(OPND,b); Pop(OPND,a); Push(OPND,Operate(a,theta,b)); break; } } return GetTop(OPND); }
Eric Z
source share