在我的程序中,我正在从中缀转换为后缀。我有一个名为 isOperator() 的方法,如果运算符的优先级大于 0,它将返回 true。
我应该使用 isOperator() 重写 toPostfix() 方法,但我不确定从哪里开始。
public class Expression {
private static final String SPACE = " ";
private static final String PLUS = "+";
private static final String MINUS = "-";
public static int rank(String operator) {
switch (operator) {
case "*":
case "/":
return 2;
case PLUS:
case MINUS: //2
return 1;
default:
return -1;
}
}
public static boolean isOperator(String token) { //4
if (rank(token) > 0){
return true;
}
return false;
}
public static String toPostfix(String infixExpr) {
StringBuilder output = new StringBuilder();
Stack<String> operators = new ArrayStack<>();
for (String token: infixExpr.split("\\s+")) {
if (rank(token) > 0) { // operator
// pop equal or higher precedence
while (!operators.isEmpty() &&
rank(operators.peek()) >= rank(token)) {
output.append(operators.pop() + SPACE);
}
operators.push(token);
} else { // operand
output.append(token + SPACE);
}
}
while (!operators.isEmpty()) {
output.append(operators.pop() + SPACE);
}
return output.toString();
}
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d / e / f";
System.out.println(toPostfix(infix));
}
}