template <class Type> class ExpNode { public: int type; union { Type opnd; char optr;}; ExpNode() : type(INFIX), optr('=') {} ExpNode(Type opnd) : type(OPND), opnd(opnd) {} ExpNode(char optr) : type(OPTR), optr(optr) {} };
template <class Type> class Expression : List<ExpNode<Type> > { public: void Input() { MakeEmpty(); Get()->type =INFIX; cout << endl << "输入表达式,以=结束输入" << endl; Type opnd; char optr = ' '; while (optr != '=') { cin >> opnd; if (opnd != 0) { ExpNode<Type> newopnd(opnd); LastInsert(newopnd); } cin >> optr; ExpNode<Type> newoptr(optr); LastInsert(newoptr); } } void Print() { First(); cout << endl; for (ExpNode<Type> *p = Next(); p != NULL; p = Next() ) { switch (p->type) { case OPND: cout << p->opnd; break; case OPTR: cout << p->optr; break; default: break; } cout << ' '; } cout << endl; } Expression & Postfix() //将中缀表达式转变为后缀表达式 { First(); if (Get()->type == POSTFIX) return *this; Stack<char> s; s.Push('='); Expression temp; ExpNode<Type> *p = Next(); while (p != NULL) { switch (p->type) { case OPND: temp.LastInsert(*p); p = Next(); break; case OPTR: while (isp(s.GetTop()) > icp(p->optr) ) { ExpNode<Type> newoptr(s.Pop()); temp.LastInsert(newoptr); } if (isp(s.GetTop()) == icp(p->optr) ) { s.Pop(); p =Next(); break; } s.Push(p->optr); p = Next(); break; default: break; } } *this = temp; pGetFirst()->data.type = POSTFIX; return *this; }
Type Calculate() { Expression temp = *this; if (pGetFirst()->data.type != POSTFIX) temp.Postfix(); Stack<Type> s; Type left, right; for (ExpNode<Type> *p = temp.Next(); p != NULL; p = temp.Next()) { switch (p->type) { case OPND: s.Push(p->opnd); break; case OPTR: right = s.Pop(); left = s.Pop(); switch (p->optr) { case '+': s.Push(left + right); break; case '-': s.Push(left - right); break; case '*': s.Push(left * right); break; case '/': if (right != 0) s.Push(left/right); else return 0; break; // case '%': if (right != 0) s.Push(left%right); else return 0; break; // case '^': s.Push(Power(left, right)); break; default: break; } default: break; } } return s.Pop(); }
private: int isp(char optr) { switch (optr) { case '=': return 0; case '(': return 1; case '^': return 7; case '*': return 5; case '/': return 5; case '%': return 5; case '+': return 3; case '-': return 3; case ')': return 8; default: return 0; } }
int icp(char optr) { switch (optr) { case '=': return 0; case '(': return 8; case '^': return 6; case '*': return 4; case '/': return 4; case '%': return 4; case '+': return 2; case '-': return 2; case ')': return 1; default: return 0; } } };
private: int tellerNum; int simuTime; int curTime, nextTime; int customerNum; long customerTime; int arrivalLow, arrivalHigh, arrivalRange; int serviceLow, serviceHigh, serviceRange; Teller tellers[21]; Queue<int> customer;