问题:输入一个逆波兰表达式(后缀表达式),使用栈(stack)计算其结果
支持小括号和多位数整数
思路分析:
逆波兰计算器,从左向右扫描表达式,遇到数字将数字压入栈中,遇到运算符时,将栈中栈顶的两个数据压出,并通过运算符进行计算,然后将其结果再次压入栈中,重复上述操作,直到表达式末尾。
例如:计算(3 + 4)* 5 - 6对应的后缀表达式3 4 + 5 * 6 -,步骤如下:
第一步:将3 压入栈中
第二步:同第一步,将 4 压入栈中
第三步:遇到 + ,将 4 和 3 弹出,并计算,将结果再次压入栈中
第四步:将 5 压入栈中
第五步:遇到 * 将 5 和 7 压出栈,并计算,再将计算的结果压入栈
第六步:将 6 压入栈中
第七步:取出 35 和 6 并计算他们之间的结果,将结果压入栈
代码实现:
package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
// 先定义一个波兰表达式
// (3 + 4) * 5 - 6 => 3 4 + 5 * 6 -
String suffixExpression = "3 4 + 5 * 6 -";
// 1. 先将 波兰表达式 放到 ArrayList 中,方便读取
List<String> list = getListString(suffixExpression);
System.out.println("链表的内容为 " + list);
// 2.遍历 list 配合栈完成计算
System.out.printf("表达式 (3+4)*5-6 = %d",calculate(list));
}
// 完成对 逆波兰表达式的计算
public static int calculate(List<String> list){
Stack<String> stack = new Stack<>();
// 遍历 list
for(String s : list){
// 这里使用正则表达式
if(s.matches("\\d+")){
stack.push(s);
}else {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0;
if (s.equals("+")) {
res = num1 + num2;
} else if (s.equals("-")) {
res = num2 - num1;
} else if (s.equals("*")) {
res = num1 * num2;
} else if (s.equals("/")) {
res = num2 / num1;
} else {
throw new RuntimeException("运算符出错~");
}
stack.push(res + ""); // 自己写的时候这块出错了
}
}
return Integer.parseInt(stack.pop());
}
// 将一个逆波兰表达式(数据 + 运算符)放到 list 中
public static List<String> getListString(String suffixExpression){
String[] str = suffixExpression.split(" ");
List<String> list = new ArrayList<>();
for(String item : str){
list.add(item);
}
return list;
}
}