1.

 /*************************************************************************
* Exercise 1.3.10
*
* % java InfixToPostfix
* ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
* 1 2 3 + 4 5 * * +
*
* % java InfixToPostfix
* ( sqrt ( 1 + 2 ) )
* 1 2 + sqrt
*
*************************************************************************/ public class InfixToPostfix
{
public static void main(String[] args)
{
Stack<String> ops = new Stack<String>();
Stack<String> vals = new Stack<String>(); while (!StdIn.isEmpty())
{
String s = StdIn.readString(); if (s.equals("(")) ;
else if (s.equals("+") ||
s.equals("-") ||
s.equals("*") ||
s.equals("/") ||
s.equals("sqrt")) ops.push(s);
else if (s.equals(")"))
{
String op = ops.pop();
String v = vals.pop(); if (op.equals("+") ||
op.equals("-") ||
op.equals("*") ||
op.equals("/"))
v = String.format("%s %s %s", vals.pop(), v, op);
else if (op.equals("sqrt"))
v = String.format("%s %s", v, op); vals.push(v);
}
else vals.push(s);
} StdOut.println(vals.pop());
}
}

2.

 /*************************************************************************
* Exercise 1.3.11
*
* % java EvaluatePostfix
* 1 2 3 + 4 5 * * +
* 101.0
*
* % java EvaluatePostfix
* 1 5 sqrt + 2.0 /
* 1.618033988749895
*
* % java EvaluatePostfix
* 12 9 - 105 7 / *
* 45.0
*
* % java InfixToPostfix | java EvaluatePostfix
* ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
* 101.0
*
* % java InfixToPostfix | java EvaluatePostfix
* ( ( 1 + sqrt ( 5 ) ) / 2.0 )
* 1.618033988749895
*
*************************************************************************/ public class EvaluatePostfix
{
public static void main(String[] args)
{
Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty())
{
String s = StdIn.readString(); if (s.equals("(") ||
s.equals(")")) ;
else if (s.equals("+") ||
s.equals("-") ||
s.equals("*") ||
s.equals("/") ||
s.equals("sqrt"))
{
double v = 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;
else if (s.equals("/")) v = vals.pop() / v;
else if (s.equals("sqrt")) v = Math.sqrt(v); vals.push(v);
}
else
vals.push(Double.parseDouble(s));
} StdOut.println(vals.pop());
}
}
05-16 17:22