代码实现
package com.springboot.数据结构.stack.polandNotaion;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author: 牧羊
* @Date: 2020/5/6 9:16
* 逆波兰表达式运算
*/
public class PolandNotation {
public static void main(String[] args) {
//先定义逆波兰式
//测试
//说明为了方便,逆波兰式的数字额符号隔开使用
//String suffixExpression = "30 4 + 5 * 6 -";
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";
//思路
//1:先将"3 4 + 5 X 6 -" 放到ArrayList当中
//2:将ArrayList传递给一个方法,遍历ArrayList配合栈完成运算
List<String> listString = getListString(suffixExpression);
System.out.println("listString = " + listString);
int res = calculate(listString);
System.out.println("计算结果是:" + res);
}
//将一个波兰表达式,依次将数据和运算符,放入到ArrayList当中
public static List<String> getListString(String suffixExpression){
//将suffixExpression分割
String[] spilt = suffixExpression.split(" ");
List<String> list = new ArrayList<>();
for(String ele : spilt){
list.add(ele);
}
return list;
}
//完成对逆波兰表达式的运算
/**
* 1:从左至右进行扫描,将3和4压入堆栈
* 2:遇到+运算符,因此弹出4和3(4为栈顶元素,3位次栈顶元素)计算出,3+4的值,得7,再将7压入栈
* 3:将5压入栈中
* 4:接下来是X运算符,因此弹出5和7,计算出7X5=35,将35入栈
* 5:将6入栈
* 6:最后是-运算符,计算出35-6的值,即29,由此得出最终答案
*/
public static int calculate(List<String> ls){
//创建数栈,只需要一个栈就可以
Stack<String> stack = new Stack<>();
//遍历ls
for(String item : ls){
//这里使用正则表达式来取出数
if(item.matches("\\d+")){ //数字
//入栈
stack.push(item);
}else{ //符号
//pop出两个数,并运算,再入栈
Integer num2 = Integer.valueOf(stack.pop());
Integer num1 = Integer.valueOf(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{
throw new RuntimeException("运算符有误");
}
//把res入栈
stack.push("" + res);
}
}
//最后留在stack中的数据是运算结果
return Integer.valueOf(stack.pop());
}
}