图来自该视频中讲师的分析,实现代码如下:
在这里插入代码片package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//先定义逆波兰表达式
//(3+4)*5-6 => 3 4 + 5 * 6 -
//说明为了方便,逆波兰表达式的数字和符号使用空格隔开
String suffixExpression = "3 4 + 5 * 6 -";
//思路 1、将 表达式放到ArrayList中
//2、将ArrayList 配合栈完成计算
List<String> rpnList = getListString(suffixExpression);
System.out.println("rpnList=" + rpnList);
int res = cal(rpnList);
System.out.println("输出结果为:"+res);
}
public static List<String> getListString(String suffixExpression){
//将字符串以空格为标识 隔开取数进list
String[] split = suffixExpression.split(" ");
List<String> List = new ArrayList<String>();
for(String ele: split) {
List.add(ele);
}
return List;
}
//完成对逆波兰表达式的运算
public static int cal(List<String> ls) {
Stack<String> stack = new Stack<String>();
for(String item:ls) {
//正则表达式取出数
if(item.matches("\\d+")) {
stack.push(item);
}else {
//pop出两个数并运算
int num2 = Integer.parseInt(stack.pop().trim());//讲师所写的代码为int num2 = Integer.parseInt(stack.pop());但是代码运行后会编译错误,具体原因这篇博客有分析(非本人博客):[关于Exception in thread "main" java.lang.NumberFormatException: For input string: " 1 "的原因和解决方法](https://blog.csdn.net/weixin_44089360/article/details/104683806)
int num1 = Integer.parseInt(stack.pop().trim());
int res = 0;
if(item.equals("+")) {
res = num1 + num2;
}else if(item.equals("-")) {
res = num1 - num2;
}else if(item.equals("*")) {
res = num1 * num2;
}else if(item.equals("/")) {
res = num1 / num2;
}else {
throw new RuntimeException("运算符有误");
}
stack.push(" " + res);
}
}
return Integer.parseInt(stack.pop().trim());
}
}