An expression consists of parentheses, operators, and operands (numbers. In the following 4 cases, these entities are sent to the stack one by one from left to right.
(1) Push the operand to the operand stack;
(2) Push operators into the operator stack;
(3) Ignore the left parenthesis;
(4) In case of right parenthesis, an operator is displayed, a required number of operators are displayed, and the operation results of operators and operators are pushed to the operand stack.
Dijastra's two-Stack arithmetic expression evaluate Algorithm]
Public class evaluate {public static void main (string [] ARGs) {stack <string> Ops = new stack <string> (); stack <double> Vals = new stack <double> (); While (! Stdin. isempty () {string S = stdin. readstring (); If (S. equals ("(") continue; else if (S. equals ("+") Ops. push (s); else if (S. equals ("-") Ops. push (s); else if (S. equals ("*") Ops. push (s); else if (S. equals ("/") Ops. push (s); else if (S. equals ("SQRT") Ops. push (s); else if (S. equals (")") {string op = ops. pop (); Double V = Vals. pop (); If (op. equals ("+") V = Vals. pop () + V; else if (op. equals ("-") V = Vals. pop ()-V; else if (op. equals ("*") V = Vals. pop () * V; else if (op. equals ("/") V = Vals. pop ()/V; else if (op. equals ("SQRT") V = math. SQRT (V); Vals. push (V);} // if the character is neither operator nor parentheses, press it as a double value into the stack else Vals. push (double. parsedouble (s);} system. out. println (Vals. pop ());}}
Page80-stack Use Case-arithmetic expression evaluate