从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 和 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果
我们完成一个逆波兰计算器,要求完成如下任务:
- 输入一个逆波兰表达式(后缀表达式),使用栈(Stack), 计算其结果
- 支持小括号和多位数整数,因为这里我们主要讲的是数据结构,因此计算器进行简化,只支持对整数的计算。
- 思路分析
- 代码完成
public class LastCalculator {
public static void main(String[] args) {
String antiPoland = "3 4 + 5 * 6 -";
ArrayList<String> anitPoland = spitAnitPoland(antiPoland);
System.out.println(anitPoland);
Integer excute = excute(anitPoland);
System.out.println(excute);
}
// 将得到的逆波兰字符串转换成数组存储
public static ArrayList<String> spitAnitPoland(String antiPoland){
ArrayList<String> list = new ArrayList<>();
String[] s = antiPoland.split(" ");
for (String s1 : s) {
list.add(s1);
}
return list;
}
/**
* 1. 从左至右扫描,将3和4压入堆栈;
* 2. 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
* 3. 将5入栈;
* 4. 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
* 5. 将6入栈;
* 6. 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
*/
public static Integer excute(ArrayList<String> anitPoland) {
Stack<Integer> numStack = new Stack<>();
for (String item : anitPoland) {
// 1. 从左至右扫描,将3和4压入堆栈;
if (item.matches("\\d+")) {
numStack.push(Integer.parseInt(item));
}else {
Integer num2 = numStack.pop();
Integer num1 = numStack.pop();
Integer calc = calc(num1, num2, item);
numStack.push(calc);
}
}
return numStack.pop();
}
// 计算方法
public static Integer calc(Integer num1,Integer num2,String oper) {
int res;
if (oper.equals("+")) {
res = num1 + num2;
} else if (oper.equals("-")) {
res = num1 - num2;
} else if (oper.equals("*")) {
res = num1 * num2;
} else if (oper.equals("/")) {
res = num1 / num2;
} else {
throw new RuntimeException("运算符有误");
}
return res;
}
}