Java Dijkstra双栈算数表达式求值算法
作者:互联网
/**
* ( 1 + ( ( 6 - 3 ) * ( 10 / 5 ) ) )
*
* @Author ZhangGJ
* @Date 2020/12/15 07:24
*/
public class Evaluate {
public static void main(String[] args) {
Stack<String> operator = new Stack<>();
Stack<Double> value = new Stack<>();
while (!StdIn.isEmpty()) {
String s = StdIn.readString();
if (s.equals("(")) {
;
} else if (s.equals("+")) {
operator.push(s);
} else if (s.equals("-")) {
operator.push(s);
} else if (s.equals("*")) {
operator.push(s);
} else if (s.equals("/")) {
operator.push(s);
} else if (s.equals("sqrt")) {
operator.push(s);
} else if (s.equals(")")) {
String op = operator.pop();
double v = value.pop();
if (op.equals("+")) {
v = value.pop() + v;
} else if (op.equals("-")) {
v = value.pop() - v;
} else if (op.equals("*")) {
v = value.pop() * v;
} else if (op.equals("/")) {
v = value.pop() / v;
} else if (op.equals("sqrt")) {
v = Math.sqrt(v);
}
value.push(v);
} else {
value.push(Double.parseDouble(s));
}
}
StdOut.println(value.pop());
}
}
Result:
( 1 + ( ( 6 - 3 ) * ( 10 / 5 ) ) )
7.0
标签:Java,push,equals,value,else,operator,pop,双栈,求值 来源: https://blog.csdn.net/qq_41133155/article/details/111242370