运算表达式 栈应用
数据结构课作业栈应用之运算表达式求值。
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] = '\0'; 104 sscanf (tmp, "%d", &a); 105 Number.push (a); 106 } 107 else 108 { 109 switch (Precede (Operator.top(), ch)) 110 { 111 case '<': 112 Operator.push (ch); 113 ch = exp[i++]; 114 break; 115 case '=': 116 Operator.pop (); 117 ch = exp[i++]; 118 break; 119 case '>': 120 char opt = Operator.top (); 121 Operator.pop(); 122 int A = Number.top (); 123 Number.pop(); 124 int B = Number.top (); 125 Number.pop(); 126 Number.push (Opera (B, opt, A)); 127 break; 128 } 129 } 130 131 } 132 return Number.top(); 133 } 134 135 int main() 136 { 137 string exp; 138 while (1) 139 { 140 cout << "*** 请输入一个表达式 ***\n" 141 "注意:以'#'结尾且中间不得有多余的空格 :\n";cin >> exp; 142 143 int ans = Expression (exp); 144 145 printf ("%d\n",ans); 146 } 147 return 0; 148 }