package day7;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class nibolan {
public static void main(String[] args) {
//先定义一个逆波兰
String nibolan ="3 4 + 5 * 6 -";
day7.nibolan nibolan1 = new nibolan();
List<String> list= getliststring(nibolan);
System.out.println(list);
int res =nibolan1.yunsuan(list);
System.out.println(res);
}
// 将一个逆波兰式,依次将数据和运算符加入ArrayList中
public static List<String> getliststring(String nibolan){
String[] split =nibolan.split(" ");//用空格分割字符串
ArrayList<String> list = new ArrayList<>(); //创建数组保存字符
for (String ele:split){ //for循环的增强
list.add(ele); //把字符加入到数组中
}
// for(int i =0;i<split.length;i++){
// list.add(split[i]);
// }
return list;
}
// 对逆波兰式的运算
// 从左到右扫描,遇到数字就入栈,遇到符号将数字出栈,计算结果,然后将计算结果入栈,
// 接下来继续入栈。最后得到结果,返回他的值。
public int yunsuan(List<String> list){
Stack<String> stack = new Stack<>();
// 遍历list
for (String li :list){
if (li.matches("\\d+")) //匹配数字
{
stack.push(li);
}
else {
int b =Integer.parseInt(stack.pop());
int a =Integer.parseInt(stack.pop());// 因为前面的先入栈,所以他出的在后面,计算就在前
int res =0;
if (li.equals("+")){
res =a+b;
}
else if (li.equals("-")){
res =a-b;
}
else if (li.equals("*")){
res=a*b;
}
else if(li.equals("/")){
res=a/b;
}
else {
throw new RuntimeException("运算符错误");
}
stack.push(res+""); //吧int转换为string
}
}
return Integer.parseInt(stack.pop());
}
}
后缀表达式(逆波兰式)表达式的计算
于 2022-08-12 11:02:18 首次发布