大家看到,后缀表达式适合计算式进行运算,但是人却不太容易写出来,尤其是表达式很长的情况下,因此在开发中,我们需要将 中缀表达式转成后缀表达式。

具体步骤如下:

  1. 初始化两个栈:运算符栈s1和储存中间结果的栈s2;
  2. 从左至右扫描中缀表达式;
  3. 遇到操作数时,将其压s2;
  4. 遇到运算符时,比较其与s1栈顶运算符的优先级:
  5. 如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
  6. 否则,若优先级比栈顶运算符的高,也将运算符压入s1;
  7. 否则,将s1栈顶的运算符弹出并压入到s2中,再次转到(4-1)与s1中新的栈顶运算符相比较;
  1. 遇到括号时: (1) 如果是左括号“(”,则直接压入s1 (2) 如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
  2. 重复步骤2至5,直到表达式的最右边
  3. 将s1中剩余的运算符依次弹出并压入s2
  4. 依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式

哔哩哔哩动画

举例说明:

将中缀表达 式“1+((2+3)×4)-5”转 换为后缀表达式的过 程如下
因此结果为
"1 2 3 + 4 × + 5 –"

| 扫描到的元素 | s2(栈底->栈顶) | s1 (栈底->栈顶) | 说明 | | —- | —- | —- | —- |

| 1 | 1 | 空 | 数字,直接入栈 |

| + | 1 | + | s1为空,运算符直接入栈 |

| ( | 1 | + ( | 左括号,直接入栈 |

| ( | 1 | + ( ( | 同上 |

| 2 | 1 2 | + ( ( | 数字 |

| + | 1 2 | + ( ( + | s1栈顶为左括号,运算符直接入栈 |

| 3 | 1 2 3 | + ( ( + | 数字 |

| ) | 1 2 3 + | + ( | 右括号,弹出运算符直至遇到左括号 |

| × | 1 2 3 + | + ( × | s1栈顶为左括号,运算符直接入栈 |

| 4 | 1 2 3 + 4 | + ( × | 数字 |

| ) | 1 2 3 + 4 × | + | 右括号,弹出运算符直至遇到左括号 |

| - | 1 2 3 + 4 × + | - | -与+优先级相同,因此弹出+,再压入- |

| 5 | 1 2 3 + 4 × + 5 | - | 数字 |

| 到达最右端 | 1 2 3 + 4 × + 5 - | 空 | s1中剩余的运算符 |

代码实现
img

完整代码

  1. package com.atguigu.stack;
  2. /**
  3. * ClassName: <br/>
  4. * Description: <br/>
  5. * Date: 2021-02-20 14:27 <br/>
  6. * @project data_algorithm
  7. * @package com.atguigu.stack
  8. */
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Stack;
  12. public class PolandNotation {
  13. public static void main(String[] args) {
  14. //完成将一个中缀表达式转成后缀表达式的功能
  15. //说明
  16. //1. 1+((2+3)×4)-5 => 转成 1 2 3 + 4 × + 5 –
  17. //2. 因为直接对str 进行操作,不方便,因此 先将 "1+((2+3)×4)-5" =》 中缀的表达式对应的List
  18. // 即 "1+((2+3)×4)-5" => ArrayList [1,+,(,(,2,+,3,),*,4,),-,5]
  19. //3. 将得到的中缀表达式对应的List => 后缀表达式对应的List
  20. // 即 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–]
  21. String expression = "1+((2+3)*4)-5";//注意表达式
  22. List<String> infixExpressionList = toInfixExpressionList(expression);
  23. System.out.println("中缀表达式对应的List=" + infixExpressionList); // ArrayList [1,+,(,(,2,+,3,),*,4,),-,5]
  24. List<String> suffixExpreesionList = parseSuffixExpreesionList(infixExpressionList);
  25. System.out.println("后缀表达式对应的List" + suffixExpreesionList); //ArrayList [1,2,3,+,4,*,+,5,–]
  26. System.out.printf("expression=%d", calculate(suffixExpreesionList)); // ?
  27. /*
  28. //先定义给逆波兰表达式
  29. //(30+4)×5-6 => 30 4 + 5 × 6 - => 164
  30. // 4 * 5 - 8 + 60 + 8 / 2 => 4 5 * 8 - 60 + 8 2 / +
  31. //测试
  32. //说明为了方便,逆波兰表达式 的数字和符号使用空格隔开
  33. //String suffixExpression = "30 4 + 5 * 6 -";
  34. String suffixExpression = "4 5 * 8 - 60 + 8 2 / +"; // 76
  35. //思路
  36. //1. 先将 "3 4 + 5 × 6 - " => 放到ArrayList中
  37. //2. 将 ArrayList 传递给一个方法,遍历 ArrayList 配合栈 完成计算
  38. List<String> list = getListString(suffixExpression);
  39. System.out.println("rpnList=" + list);
  40. int res = calculate(list);
  41. System.out.println("计算的结果是=" + res);
  42. */
  43. }
  44. //即 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–]
  45. //方法:将得到的中缀表达式对应的List => 后缀表达式对应的List
  46. public static List<String> parseSuffixExpreesionList(List<String> ls) {
  47. //定义两个栈
  48. Stack<String> s1 = new Stack<String>(); // 符号栈
  49. //说明:因为s2 这个栈,在整个转换过程中,没有pop操作,而且后面我们还需要逆序输出
  50. //因此比较麻烦,这里我们就不用 Stack<String> 直接使用 List<String> s2
  51. //Stack<String> s2 = new Stack<String>(); // 储存中间结果的栈s2
  52. List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2
  53. //遍历ls
  54. for(String item: ls) {
  55. //如果是一个数,加入s2
  56. if(item.matches("\\d+")) {
  57. s2.add(item);
  58. } else if (item.equals("(")) {
  59. s1.push(item);
  60. } else if (item.equals(")")) {
  61. //如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
  62. while(!s1.peek().equals("(")) {
  63. s2.add(s1.pop());
  64. }
  65. s1.pop();//!!! 将 ( 弹出 s1栈, 消除小括号
  66. } else {
  67. //当item的优先级小于等于s1栈顶运算符, 将s1栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较
  68. //问题:我们缺少一个比较优先级高低的方法
  69. while(s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item) ) {
  70. s2.add(s1.pop());
  71. }
  72. //还需要将item压入栈
  73. s1.push(item);
  74. }
  75. }
  76. //将s1中剩余的运算符依次弹出并加入s2
  77. while(s1.size() != 0) {
  78. s2.add(s1.pop());
  79. }
  80. return s2; //注意因为是存放到List, 因此按顺序输出就是对应的后缀表达式对应的List
  81. }
  82. //方法:将 中缀表达式转成对应的List
  83. // s="1+((2+3)×4)-5";
  84. public static List<String> toInfixExpressionList(String s) {
  85. //定义一个List,存放中缀表达式 对应的内容
  86. List<String> ls = new ArrayList<String>();
  87. int i = 0; //这时是一个指针,用于遍历 中缀表达式字符串
  88. String str; // 对多位数的拼接
  89. char c; // 每遍历到一个字符,就放入到c
  90. do {
  91. //如果c是一个非数字,我需要加入到ls
  92. if((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57) {
  93. ls.add("" + c);
  94. i++; //i需要后移
  95. } else { //如果是一个数,需要考虑多位数
  96. str = ""; //先将str 置成"" '0'[48]->'9'[57]
  97. while(i < s.length() && (c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) {
  98. str += c;//拼接
  99. i++;
  100. }
  101. ls.add(str);
  102. }
  103. }while(i < s.length());
  104. return ls;//返回
  105. }
  106. //将一个逆波兰表达式, 依次将数据和运算符 放入到 ArrayList中
  107. public static List<String> getListString(String suffixExpression) {
  108. //将 suffixExpression 分割
  109. String[] split = suffixExpression.split(" ");
  110. List<String> list = new ArrayList<String>();
  111. for(String ele: split) {
  112. list.add(ele);
  113. }
  114. return list;
  115. }
  116. //完成对逆波兰表达式的运算
  117. /*
  118. * 1)从左至右扫描,将3和4压入堆栈;
  119. 2)遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
  120. 3)将5入栈;
  121. 4)接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
  122. 5)将6入栈;
  123. 6)最后是-运算符,计算出35-6的值,即29,由此得出最终结果
  124. */
  125. public static int calculate(List<String> ls) {
  126. // 创建给栈, 只需要一个栈即可
  127. Stack<String> stack = new Stack<String>();
  128. // 遍历 ls
  129. for (String item : ls) {
  130. // 这里使用正则表达式来取出数
  131. if (item.matches("\\d+")) { // 匹配的是多位数
  132. // 入栈
  133. stack.push(item);
  134. } else {
  135. // pop出两个数,并运算, 再入栈
  136. int num2 = Integer.parseInt(stack.pop());
  137. int num1 = Integer.parseInt(stack.pop());
  138. int res = 0;
  139. if (item.equals("+")) {
  140. res = num1 + num2;
  141. } else if (item.equals("-")) {
  142. res = num1 - num2;
  143. } else if (item.equals("*")) {
  144. res = num1 * num2;
  145. } else if (item.equals("/")) {
  146. res = num1 / num2;
  147. } else {
  148. throw new RuntimeException("运算符有误");
  149. }
  150. //把res 入栈
  151. stack.push("" + res);
  152. }
  153. }
  154. //最后留在stack中的数据是运算结果
  155. return Integer.parseInt(stack.pop());
  156. }
  157. }
  158. //编写一个类 Operation 可以返回一个运算符 对应的优先级
  159. class Operation {
  160. private static int ADD = 1;
  161. private static int SUB = 1;
  162. private static int MUL = 2;
  163. private static int DIV = 2;
  164. //写一个方法,返回对应的优先级数字
  165. public static int getValue(String operation) {
  166. int result = 0;
  167. switch (operation) {
  168. case "+":
  169. result = ADD;
  170. break;
  171. case "-":
  172. result = SUB;
  173. break;
  174. case "*":
  175. result = MUL;
  176. break;
  177. case "/":
  178. result = DIV;
  179. break;
  180. default:
  181. System.out.println("不存在该运算符" + operation);
  182. break;
  183. }
  184. return result;
  185. }
  186. }