1、源码

PolandNotation类

  1. package com.study.stack;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Stack;
  5. public class PolandNotation {
  6. public static void main(String[] args) {
  7. //定义一个逆波兰表达式
  8. //(3+4)*5-6 -> 3 4 + 5 * 6 -
  9. String suffixExpression = "3 4 + 5 * 6 -";
  10. List<String> listString = getListString(suffixExpression);
  11. System.out.println(listString);
  12. int res = calculate(listString);
  13. System.out.println(res);
  14. }
  15. public static List<String> getListString(String suffixExpression){
  16. String[] s = suffixExpression.split(" ");
  17. List<String> list = new ArrayList<>();
  18. for (String arr : s) {
  19. list.add(arr);
  20. }
  21. return list;
  22. }
  23. public static int calculate(List<String> ls){
  24. Stack<String> stack = new Stack<>();
  25. for (String l : ls) {
  26. if (l.matches("\\d+")){
  27. stack.push(l);
  28. }else {
  29. int num2 = Integer.parseInt(stack.pop());
  30. int num1 = Integer.parseInt(stack.pop());
  31. int res = 0;
  32. if(l.equals("+")){
  33. res =num1+num2;
  34. }else if (l.equals("-")){
  35. res = num1-num2;
  36. }else if (l.equals("*")){
  37. res = num1*num2;
  38. }else if (l.equals("/")){
  39. res = num1/num2;
  40. }else {
  41. throw new RuntimeException("运算符有误");
  42. }
  43. stack.push(""+res);
  44. }
  45. }
  46. return Integer.parseInt(stack.pop());
  47. }
  48. }

测试结果
图片.png