#ifndef EXPression_H #define Expression_H #include "List.h" #include "Stack.h" #define INFIX 0 #define POSTFIX 1 #define OPND 4 #define OPTR 8 template 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 Expression : List > { public: void Input() { MakeEmpty(); Get()->type =INFIX; cout << endl << "输入表达式,以=结束输入" << endl; Type opnd; char optr = ' '; while (optr != '=') { cin >> opnd; if (opnd != 0) { ExpNode newopnd(opnd); LastInsert(newopnd); } cin >> optr; ExpNode newoptr(optr); LastInsert(newoptr); } } void Print() { First(); cout << endl; for (ExpNode *p = Next(); p != NULL; p = Next() ) { switch (p->type) { case OPND: cout << p->opnd; break; case OPTR: cout << p->optr; break; default: break; } } cout << endl; } Expression & Postfix() //将中缀表达式转变为后缀表达式 { First(); if (Get()->type == POSTFIX) return *this; Stack s; s.Push('='); Expression temp; ExpNode *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 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() { if (pGetFirst()->data.type != POSTFIX) temp.Postfix(); Stack s; Type left, right; for (ExpNode *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; } } }; #endif |