Ex1_3_11 计算后序表达式
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Ex1_3_11 {
public static void main(String[] args){
Stack<Double> vols = new Stack<>();
while (!StdIn.isEmpty()){
String s = StdIn.readString();
double vol = 0;
switch (s){
case "+":
vol = vols.pop() + vols.pop();
vols.push(vol);
break;
case "-":
vol = -vols.pop() + vols.pop();
vols.push(vol);
break;
case "*":
vol = vols.pop() * vols.pop();
vols.push(vol);
break;
case "/":
vol = 1/vols.pop() * vols.pop();
vols.push(vol);
break;
case "sqrt":
vol = Math.sqrt(vols.pop());
vols.push(vol);
break;
default:
vol = Double.parseDouble(s);
vols.push(vol);
break;
}
}
StdOut.println(vols.pop());
}
}
要点:
- 使用双栈法变形
- 注意pop出的顺序