1.
1 /*************************************************************************2 * Exercise 1.3.103 * 4 *% java infixtopostfix5 * (1 + ((2 + 3) * (4 * 5)))6 * 1 2 3 + 4 5 * * +7 * 8 *% java infixtopostfix9 * (sqrt (1 + 2))Ten * 1 2 + sqrt One * A *************************************************************************/ - - Public classInfixtopostfix the { - Public Static voidMain (string[] args) - { -stack<string> Ops =NewStack<string>(); +Stack<string> Vals =NewStack<string>(); - + while(!stdin.isempty ()) A { atString s =stdin.readstring (); - - if(S.equals ("(")) ; - Else if(S.equals ("+") | | -S.equals ("-") | | -S.equals ("*") | | inS.equals ("/") | | -S.equals ("sqrt") ) Ops.push (s); to Else if(S.equals (")")) + { -String op =Ops.pop (); theString v =Vals.pop (); * $ if(Op.equals ("+") | |Panax NotoginsengOp.equals ("-") | | -Op.equals ("*") | | theOp.equals ("/")) +v = String.Format ("%s%s%s", Vals.pop (), V, op); A Else if(Op.equals ("sqrt")) thev = String.Format ("%s%s", V, op); + - Vals.push (v); $ } $ ElseVals.push (s); - } - the stdout.println (Vals.pop ()); - }Wuyi}
2.
1 /*************************************************************************2 * Exercise 1.3.113 * 4 *% java evaluatepostfix5 * 1 2 3 + 4 5 * * +6 * 101.07 * 8 *% java evaluatepostfix9 * 1 5 sqrt + 2.0/Ten * 1.618033988749895 One * A *% java evaluatepostfix - * 9-105 7/* - * 45.0 the * - *% java infixtopostfix | java evaluatepostfix - * (1 + ((2 + 3) * (4 * 5))) - * 101.0 + * - *% java infixtopostfix | java evaluatepostfix + * ((1 + sqrt (5))/2.0) A * 1.618033988749895 at * - *************************************************************************/ - - Public classEvaluatepostfix - { - Public Static voidMain (string[] args) in { -Stack<double> Vals =NewStack<double>(); to + while(!stdin.isempty ()) - { theString s =stdin.readstring (); * $ if(S.equals (") | |Panax NotoginsengS.equals (")")) ; - Else if(S.equals ("+") | | theS.equals ("-") | | +S.equals ("*") | | AS.equals ("/") | | theS.equals ("sqrt")) + { - Doublev =Vals.pop (); $ $ if(S.equals ("+")) v = vals.pop () +v; - Else if(S.equals ("-")) v = vals.pop ()-v; - Else if(S.equals ("*")) v = vals.pop () *v; the Else if(S.equals ("/")) v = vals.pop ()/v; - Else if(S.equals ("sqrt")) v =math.sqrt (v);Wuyi the Vals.push (v); - } Wu Else - Vals.push (double.parsedouble (s)); About } $ - stdout.println (Vals.pop ()); - } -}
Algorithm Sedgewick Fourth Edition-1th Chapter 141 using a stack to convert a predecessor expression to a post-expression and calculate a value