package Stack.PolandNotation; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class demo03 { public static void main(String[] args) { //先定义逆波兰表达式 //(3+4)*5-6 ==> 34+5*6- String suffixexpression="30 4 + 5 * 6 -"; //为了方便,逆波兰表达式中通过空格将元素隔开 //思路: //1、先将suffexpression放到一个Arraylist里面去 //2、将ArrayList传给一个方法,配合栈完成计算 ListrpnList = getList(suffixexpression); System.out.println("rpnList="+rpnList); int res = calculate(rpnList); System.out.println("计算的结果是"+res); } //将一个逆波兰表达式,依次将数据和运算符放入ArrayList中 public static List getList(String suffixexpression){ //将suffixexpression分割 String[] s = suffixexpression.split(" "); List list= new ArrayList<>(); for (String ele : s) { list.add(ele); } return list; } public static int cal(int num1,int num2,String oper){ int res = 0; switch (oper){ case "+": res = num1+num2; break; case "-": res = num1-num2; break; case "*": res = num1*num2; break; case "/": res = num1/num2; break; } return res; } //完成对逆波兰表达式的计算 public static int calculate(List ls){ Stack stack = new Stack<>(); for (String item : ls) { if (item.matches("\d+")){//如果是数,入栈 stack.push(item); }else {//如果是符号,pop出俩数,计算完之后再入栈 int num2 = Integer.parseInt(stack.pop());//先d出的数用num2接收(右) int num1 = Integer.parseInt(stack.pop()); int res = cal(num1, num2, item); stack.push(res+""); } } //最后留在stack中的数就是结果 return Integer.parseInt(stack.pop()); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)