逆波兰表达式计算
public class PolandNotation {
public static void main(String[] args) {
//逆波兰表达式
//(3+4)*5-6 -》 3 4 + 5 * 6 -
//为了方便,逆波兰表达式的数字和符号使用空格隔开
String suffixExpression=“3 4 + 5 * 6 -”;
//1.先将“3 4 + 5 * 6 -”放到ArrayList中
//2.将ArrayList传递给一个方法,遍历ArrayList配合栈完成计算
List<String> rpnList =getList(suffixExpression);
System.out.println(rpnList);
int res =claculate(rpnList);
System.out.println(res);
}
public static List<String> getList(String suffixExpression){
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele: split){
list.add(ele);
}
return list;
}
//完成对逆波兰表达式的运算
//1.从左到右扫描,将3和4压入堆栈;
//2.遇到+运算符,弹出4和3,计算3+4的值,得7,再将7压入栈
//3.将5入栈
//4。接下来是*运算符,弹出5,7,计算7*5=35,将35入栈
//5.将6入栈
//6.最后是-运算符,计算出35-6得值得29
public static int claculate(List<String> ls){
Stack<String> st = new Stack<String>();
for (String item:ls){
if (item.matches("\\d+")){//匹配多位数
//入栈
st.push(item);
}else {
int num2 =Integer.parseInt(st.pop());
int num1 =Integer.parseInt(st.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("运算符有误");
}
st.push(res+"");
}
}
return Integer.parseInt(st.pop());
}