栈:逆波兰表达式(后缀表达式)
输入一个逆波兰表达式(后缀表达式)
例如:(3+4)*5-6对应的后缀表达式就是3 4 + 5 * 6 -,
针对后缀表达式求值步骤如下:
a. 从左到右扫描,将3 和 4压入堆栈;
b. 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
c. 将5入栈;
d. 接下来是*运算符,因此弹出5和7,计算出7*5=35,将35入栈;
e. 将6入栈;
最后是-运算符,计算出35-6的值,即29,由此得出最终结果。
代码如下
1 package com.jyj.stack; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import java.util.Stack; 6 7 public class PolandNotation { 8 public static void main(String[] args) { 9 //先定义给逆波兰表达式 10 //(3+4)*5-6 => 3 4 + 5 * 6 - 11 //说明:为了方便,逆波兰表达式的数字和符号使用空格隔开 12 String suffixExpression = "3 4 + 5 * 6 -"; 13 List<String> list = getListString(suffixExpression); 14 System.out.println("list = "+list); 15 16 int res = calculate(list); 17 System.out.println("res = "+res); 18 } 19 20 //将逆波兰表达式 ,依次将数据和运算符 放入到ArrayList中 21 public static List<String> getListString(String suffixExpression) { 22 //分隔逆波兰表达式 23 String[] split = suffixExpression.split(" "); 24 List<String> list = new ArrayList<String>(); 25 for(String ele:split) { 26 list.add(ele); 27 } 28 return list; 29 } 30 31 //完成逆波兰表达式计算 32 /** 33 * a.从左到右扫描,将3 和 4压入堆栈; 34 b.遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈; 35 c.将5入栈; 36 d.接下来是*运算符,因此弹出5和7,计算出7*5=35,将35入栈; 37 e.将6入栈; 38 f.最后是-运算符,计算出35-6的值,即29,由此得出最终结果。 39 */ 40 public static int calculate(List<String> list) { 41 Stack<String> stack = new Stack<String>(); 42 //遍历 43 for(String item : list) { 44 //使用正则表达式来取出数 45 if(item.matches("\\d+")) { //匹配多位数 46 //入栈 47 stack.push(item); 48 }else { 49 //pop出两个数,并运算,再入栈 50 int num2 = Integer.parseInt(stack.pop()); 51 int num1 = Integer.parseInt(stack.pop()); 52 int res = 0; 53 if(item.equals("+")) { 54 res = num1 + num2; 55 } else if(item.equals("-")) { 56 res = num1 - num2; 57 } else if(item.equals("*")) { 58 res = num1 * num2; 59 } else if(item.equals("/")) { 60 res = num1 / num2; 61 } else { 62 throw new RuntimeException("运算符有误"); 63 } 64 //把res入栈 65 stack.push(""+res); 66 } 67 } 68 return Integer.parseInt(stack.pop()); 69 } 70 } 71 72 //编写一个类 Operation 可以返回一个运算符对应的优先级 73 class Operation { 74 private static int ADD = 1; 75 private static int SUB = 1; 76 private static int MUL = 2; 77 private static int DIV = 2; 78 public static int getValue(String operation) { 79 int result = 0; 80 switch(operation) { 81 case "+": 82 result = ADD; 83 break; 84 case "-": 85 result = SUB; 86 break; 87 case "*": 88 result = MUL; 89 break; 90 case "/": 91 result = DIV; 92 break; 93 default: 94 // throw new RuntimeException("运算符有误"); 95 System.out.println("运算符有误"); 96 break; 97 } 98 return result; 99 } 100 }
以上。
朱子家训说:宜未雨而筹谋,勿临渴而掘井。
任何事情要到了跟前才想解决办法,那我们岂不很被动!