标签:中缀表达式 eval 表达式 def set 运算 ide list tor
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Stack;
public class Eval {
private static double parsePostfix(List<String> postfix) {
for (int i = 0; i < postfix.size(); i++) {
String word = postfix.get(i);
if (Operator.isSymbol(word)) {
double n1 = Double.parseDouble(postfix.get(i - 1));
double n2 = Double.parseDouble(postfix.get(i - 2));
double result = 0;
Operator symbol = Operator.value(word);
switch (symbol) {
case ADD:
result = n1 + n2;
break;
case SUBTRACT:
result = n2 - n1;
break;
case MULTIPLY:
result = n1 * n2;
break;
case DIVIDE:
result = n2 / n1;
break;
default:
break;
}
postfix.set(i, String.valueOf(result));
postfix.remove(i - 1);
postfix.remove(i - 2);
break;
}
}
if (postfix.size() == 1) {
return Double.parseDouble(postfix.get(0));
}
return parsePostfix(postfix);
}
private static List<String> infix2Postfix(List<String> infix) {
List<String> postfix = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
for (String word : infix) {
if (Operator.isSymbol(word)) {
if (stack.empty()) {
stack.push(word);
} else {
Operator symbol1 = Operator.value(stack.peek());
Operator symbol2 = Operator.value(word);
if (symbol2 == Operator.CLOSE) {
while (!stack.empty()) {
String pop = stack.pop();
1.将四则运算串分割出中缀表达式
2.将中缀表达式转换为后缀表达式
3.对后缀表达式进行求值得出结果
标签:中缀表达式 eval 表达式 def set 运算 ide list tor
原文地址:https://www.cnblogs.com/hnzj-jy192-JT/p/14646035.html