1.
1 PackageAlgorithms.util;2 3 Importalgorithms. Adt. Stack;4 5 /******************************************************************************6 * Compilation:javac Evaluate.java7 * Execution:java Evaluate8 * Dependencies:Stack.java9 *Ten * Evaluates (fully parenthesized) arithmetic expressions using One * Dijkstra ' s two-stack algorithm. A * - *% java Evaluate - * (1 + ((2 + 3) * (4 * 5))) the * 101.0 - * - *% java evaulate - * ((1 + sqrt (5))/2.0) + * 1.618033988749895 - * + * A * note:the operators, operands, and parentheses must be at * separated by whitespace. Also, each operation must - * be enclosed in parentheses. For example, you must write - * (1 + (2 + 3)) instead of (1 + 2 + 3). - * See Evaluatedeluxe.java for a fancier version. - * - * in * Remarkably, Dijkstra ' s algorithm computes the same - * answer if we put each operator *after* its and its operands to * instead of *between* them. + * - *% java Evaluate the * (1 (2 3 +) (4 5 *) *) +) * * 101.0 $ *Panax Notoginseng * Moreover, in such expressions, all parentheses is redundant! - * Removing them yields an expression known as a postfix expression. the * 1 2 3 + 4 5 * * + + * A * the ******************************************************************************/ + - Public classEvaluate { $ Public Static voidMain (string[] args) { $stack<string> Ops =NewStack<string>(); -Stack<double> Vals =NewStack<double>(); - the while(!Stdin.isempty ()) { -String s =stdin.readstring ();Wuyi if(S.equals ("(")) ; the Else if(S.equals ("+") ) Ops.push (s); - Else if(S.equals ("-") ) Ops.push (s); Wu Else if(S.equals ("*") ) Ops.push (s); - Else if(S.equals ("/") ) Ops.push (s); About Else if(S.equals ("sqrt") ) Ops.push (s); $ Else if(S.equals (")")) { -String op =Ops.pop (); - Doublev =Vals.pop (); - if(Op.equals ("+")) v = vals.pop () +v; A Else if(Op.equals ("-")) v = vals.pop ()-v; + Else if(Op.equals ("*")) v = vals.pop () *v; the Else if(Op.equals ("/")) v = vals.pop ()/v; - Else if(Op.equals ("sqrt")) v =math.sqrt (v); $ Vals.push (v); the } the ElseVals.push (double.parsedouble (s)); the } the stdout.println (Vals.pop ()); - } in}
Algorithm Sedgewick Fourth Edition-1th chapter BASIC-71 using two stacks to implement a simple compiler