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



