后缀表达式(逆波兰表达式)的计算方法
中缀表达式便于人的计算:1+((2+3)*4)-5
后缀表达式便于电脑计算:[1, 2, 3, +, 4, *, +, 5, -]
如何将中缀表达式变为后缀表达式可以参考这篇文章:
规则:从左到右遍历表达式的每个数字和符号,遇到是数字就进栈,遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,一直到最终获得结果。
/**
* @param notaion 逆波兰表达式的数组表示方式
* @return 逆波兰表达式的计算结果
*/
public static int caculate(String[] notaion) {
//1.定义一个栈,用来存储操作数
Stack<Integer> operation = new Stack<>();
//2.从左往右遍历逆波兰表达式,得到每一个元素
for (int i = 0; i < notaion.length; i++) {
String curr = notaion[i];
//3.判断当前元素是运算符还是操作数
Integer o1;
Integer o2;
Integer result;
switch (curr) {
case "+":
//4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中
o1 = operation.pop();
o2 = operation.pop();
result = o2 + o1;
operation.push(result);
break;
case "-":
//4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中
o1 = operation.pop();
o2 = operation.pop();
result = o2 - o1;
operation.push(result);
break;
case "*":
//4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中
o1 = operation.pop();
o2 = operation.pop();
result = o2 * o1;
operation.push(result);
break;
case "/":
//4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中
o1 = operation.pop();
o2 = operation.pop();
result = o2 / o1;
operation.push(result);
break;
default:
//5.操作数,把该操作数放入到栈中;
operation.push(Integer.parseInt(curr));
break;
}
}
//6.得到栈中最后一个元素,就是逆波兰表达式的结果
int result = operation.pop();
return result;
}