在实际应用中,由于中缀表达式计算的复杂度较大,并且计算式占用的空间较多,而后缀表达式在理论上可以计算任意复杂度的表达式,并且利用栈的特点每次只需要对栈顶元素进行操作即可,因而将中缀表达式转换为后缀表达式之后将会对计算效率大大提高。
后缀表达式的计算规则为:当遇到操作数(数字)时就将其入栈,当遇到操作符时就取出栈顶的两个元素,根据当前操作符进行计算,将计算结果再压入栈顶。如果表达式是规整的表达式,在整个表达式扫描完成之后栈顶将只有一个数字,该数据即为计算结果。
具体的代码如下:
import java.util.Stack;
public class LastExpression {
private static Stack<Float> stack = new Stack<>();
public static Float compute(String str) {
transfer(str);
return stack.pop();
}
private static void transfer(String str) {
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case ' ':
continue;
case '+':
plus();
break;
case '-':
sub();
break;
case '*':
mul();
break;
case '/':
div();
break;
default:
i = num(str, i);
}
}
}
private static int num(String str, int index) {
StringBuilder numStr = new StringBuilder("");
Character ch = null;
while (index < str.length() && ((ch = str.charAt(index)) <= '9' && ch >= '0')) {
numStr.append(ch);
index++;
}
stack.push(Float.parseFloat(numStr.toString()));
return index - 1;
}
private static void plus() {
Float a = stack.pop();
Float b = stack.pop();
stack.push(a + b);
}
private static void sub() {
Float a = stack.pop();
Float b = stack.pop();
stack.push(a - b);
}
private static void mul() {
Float a = stack.pop();
Float b = stack.pop();
stack.push(a * b);
}
private static void div() {
Float a = stack.pop();
Float b = stack.pop();
stack.push(a / b);
}
}