逆波兰表达式求值—java版学习
package Stack;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Stack;
/**
* n逆波兰表达式求值
* @Author: HML
* @Date: 2021/7/2 上午 9:34
* @Version 1.0
*/
public class PolandNotation {
public static void main(String[] args){
String expression = "30 4 + 5 * 6 -";
//为了方便的取数据,我们将其放入到arraylist中
List<String> list = getListString(expression);
//遍历arraylist取到值完成逆波兰表达式的计算
System.out.println(list);
int res = calculate(list);
System.out.println(res);
}
public static List<String> getListString(String exp){
//将闯进来的exp分割
String[] split = exp.split(" ");
ArrayList<String> list = new ArrayList<String>();
for (String item:split){
list.add(item);
}
return list;
}
//完成对逆波兰表达式的计算
//从左至右扫描,将3,4 压栈
//遇到+,弹出4,3 ,计算4+3,并将结果入栈
//将5入栈
//遇到*,将5,7出栈进行计算,并将35压入栈
//遇到-号,计算35-6,并将29返回即可
//这里计算应该是拿到上面list的值去计算
public static int calculate(List<String> list){
//创建一个栈
Stack<String> stack = new Stack<String>();
//遍历list
for (String item:list){
//这里考虑如何判断是运算符还是数字,故这里使用正则表达式去求值
if (item.matches("\\d+")){//这里匹配的是多位数
//数字直接入栈
System.out.println(item);
stack.push(item);
}else{
//说明是个符号
//这里要将栈顶和次栈顶的元素出栈
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
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{
//System.out.println("没有该运算符~~~");
throw new RuntimeException("没有该运算符~~~");
}
//将res入栈
stack.push(""+res);
}
}
//将最后的运算结果出栈
// System.out.println("最后的运算结果="+Integer.parseInt(stack.pop()));//这里要打印的话下一步返回会报错,因为这里已经执行了出栈操作,故这里我们不用打印它,
//把它留在主函数中进行打印即可
return Integer.parseInt(stack.pop());
}
}