Evaluate expressions (one of the applications in the data structure book stack)
Main Content: evaluate the expression, submit nyoj to pass...
The idea is to open two stacks, one operator stack, and the other operator stack ..
My code is as follows (relatively simple ):
/***** Author Gery ******/# include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Define eps 1e-9 # define ll long # define INF 0x3f3f3fusing namespace std; const int maxn = 1000 + 10; stack
Ly; stack
Gery; char str [maxn], op [maxn]; char operation [7] [7] // operator priority {'>', '>', '<', '<', '<', '>', '>'}, // '+' {'>', '>', '<', '<', '<', '>', '>'}, // '-' {'>', '>', '<', '>', '>'}, // '*' {'>', '>', '<', '> ', '>'}, // '/' {'<', '<', '= ',','}, // '(' {'>', '> '},//') '{' <',' <',', '='}, // '= '}; int get_index (char ch) {switch (ch) {case '+': return 0; case '-': return 1; case '*': return 2; case '/': return 3; case '(': return 4; case ')': return 5; case '=': return 6 ;}} char get_prio (char, char B) {int c = get_index (a); int d = get_index (B); return operation [c] [d];} double cal_value (double a, double B, char c) {switch (c) {case '+': return a + B; case '-': return a-B; case '*': return a * B; case '/': return a * 1.0/B;} int main () {int t, pd, cnt, I; double temp, left_value, right_value, val; char ch, op; scanf ("% d", & t); while (t --) {scanf ("% s", str); ly. empty (); gery. empty (); gery. push ('='); for (I = 0; I
': Op = gery. top (), gery. pop (); right_value = ly. top (), ly. pop (); left_value = ly. top (), ly. pop (); val = cal_value (left_value, right_value, Op); ly. push (val); I --; break; // After expression operation, the character pointer must be moved back }}} printf ("%. 2lf \ n ", ly. top ();} return 0;}/* 2 (-2 + 3) * 1.2 + 2) = (-2 + 3) * 10/2) = */
Later, ac saw other people use the method in the book to perform the sub-assembly, but it was too troublesome to know which method is better...