数据结构课作业栈应用之运算表达式求值。
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <string> 5 using namespace std; 6 7 #define Max 1005 8 9 template <typename T> 10 class Stack 11 { 12 public: 13 Stack ():myTop(-1) { memset (myArray, 0, sizeof myArray); } 14 bool empty () const { return myTop == -1; } 15 void push (T item); 16 void pop (); 17 T top () const; 18 private: 19 T myArray[Max]; 20 int myTop; 21 }; 22 char tmp[25]; 23 24 template <typename T> void Stack <T>::push (T item) 25 { 26 if (myTop==Max) return; 27 myArray[++myTop] = item; 28 } 29 30 template <typename T> void Stack <T>::pop () 31 { 32 if (myTop == -1) return; 33 myTop--; 34 } 35 36 template <typename T> T Stack <T>::top () const 37 { 38 if (myTop == -1) return -1; 39 return myArray[myTop]; 40 } 41 42 char OptrRelation[7][7] = 43 { 44 {'>', '>', '<', '<', '<', '>', '>'}, 45 {'>', '>', '<', '<', '<', '>', '>'}, 46 {'>', '>', '>', '>', '<', '>', '>'}, 47 {'>', '>', '>', '>', '<', '>', '>'}, 48 {'<', '<', '<', '<', '<', '=', ' '}, 49 {'>', '>', '>', '>', ' ', '>', '>'}, 50 {'<', '<', '<', '<', '<', ' ', '='} 51 }; 52 53 int Postion_Optr (char optr) 54 { 55 switch (optr) 56 { 57 case '+':return 0; 58 case '-':return 1; 59 case '*':return 2; 60 case '/':return 3; 61 case '(':return 4; 62 case ')':return 5; 63 case '#':return 6; 64 } 65 } 66 67 char Precede (char s1, char s2) 68 { 69 int coord_1 = Postion_Optr(s1); 70 int coord_2 = Postion_Optr(s2); 71 72 return OptrRelation[coord_1][coord_2]; 73 } 74 75 int Opera (int a, char op, int b) 76 { 77 if (op=='-') return a-b; 78 if (op=='+') return a+b; 79 if (op=='*') return a*b; 80 if (op=='/') return a/b; 81 } 82 83 int Expression (string exp) 84 { 85 Stack <char> Operator; 86 Stack <int> Number; 87 88 int i=0; 89 exp += "#"; 90 Operator.push ('#'); 91 92 char ch = exp[i++]; 93 while (ch!='#' || Operator.top()!='#') 94 { 95 if (ch>='0' && ch<='9') 96 { 97 int k=0, a=0; 98 while (ch<='9' && ch>='0') 99 { 100 tmp[k++] = ch; 101 ch = exp[i++]; 102 } 103 tmp[k] = '