1. /******************************************************************************
  2. * Compilation: javac EvaluateDeluxe.java
  3. * Execution: java EvaluateDeluxe
  4. * Dependencies: Stack.java
  5. *
  6. * Evaluates arithmetic expressions using Dijkstra's two-stack algorithm.
  7. * Handles the following binary operators: +, -, *, / and parentheses.
  8. *
  9. * % echo "3 + 5 * 6 - 7 * ( 8 + 5 )" | java EvaluateDeluxe
  10. * -58.0
  11. *
  12. *
  13. * Limitiations
  14. * --------------
  15. * - can easily add additional operators and precedence orders, but they
  16. * must be left associative (exponentiation is right associative)
  17. * - assumes whitespace between operators (including parentheses)
  18. *
  19. * Remarks
  20. * --------------
  21. * - can eliminate second phase if we enclose input expression
  22. * in parentheses (and, then, could also remove the test
  23. * for whether the operator stack is empty in the inner while loop)
  24. * - see http://introcs.cs.princeton.edu/java/11precedence/ for
  25. * operator precedence in Java
  26. *
  27. ******************************************************************************/
  28.  
  29. import java.util.TreeMap;
  30.  
  31. public class EvaluateDeluxe {
  32.  
  33. // result of applying binary operator op to two operands val1 and val2
  34. public static double eval(String op, double val1, double val2) {
  35. if (op.equals("+")) return val1 + val2;
  36. if (op.equals("-")) return val1 - val2;
  37. if (op.equals("/")) return val1 / val2;
  38. if (op.equals("*")) return val1 * val2;
  39. throw new RuntimeException("Invalid operator");
  40. }
  41.  
  42. public static void main(String[] args) {
  43.  
  44. // precedence order of operators
  45. TreeMap<String, Integer> precedence = new TreeMap<String, Integer>();
  46. precedence.put("(", 0); // for convenience with algorithm
  47. precedence.put(")", 0);
  48. precedence.put("+", 1); // + and - have lower precedence than * and /
  49. precedence.put("-", 1);
  50. precedence.put("*", 2);
  51. precedence.put("/", 2);
  52.  
  53. Stack<String> ops = new Stack<String>();
  54. Stack<Double> vals = new Stack<Double>();
  55.  
  56. while (!StdIn.isEmpty()) {
  57.  
  58. // read in next token (operator or value)
  59. String s = StdIn.readString();
  60.  
  61. // token is a value
  62. if (!precedence.containsKey(s)) {
  63. vals.push(Double.parseDouble(s));
  64. continue;
  65. }
  66.  
  67. // token is an operator
  68. while (true) {
  69.  
  70. // the last condition ensures that the operator with higher precedence is evaluated first
  71. if (ops.isEmpty() || s.equals("(") || (precedence.get(s) > precedence.get(ops.peek()))) {
  72. ops.push(s);
  73. break;
  74. }
  75.  
  76. // evaluate expression
  77. String op = ops.pop();
  78.  
  79. // but ignore left parentheses
  80. if (op.equals("(")) {
  81. assert s.equals(")");
  82. break;
  83. }
  84.  
  85. // evaluate operator and two operands and push result onto value stack
  86. else {
  87. double val2 = vals.pop();
  88. double val1 = vals.pop();
  89. vals.push(eval(op, val1, val2));
  90. }
  91. }
  92. }
  93.  
  94. // finished parsing string - evaluate operator and operands remaining on two stacks
  95. while (!ops.isEmpty()) {
  96. String op = ops.pop();
  97. double val2 = vals.pop();
  98. double val1 = vals.pop();
  99. vals.push(eval(op, val1, val2));
  100. }
  101.  
  102. // last value on stack is value of expression
  103. StdOut.println(vals.pop());
  104. assert vals.isEmpty();
  105. assert ops.isEmpty();
  106. }
  107. }

算法Sedgewick第四版-第1章基础-020一按优先级计算表达式的值的更多相关文章

  1. 算法Sedgewick第四版-第1章基础-001递归

    一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...

  2. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)

    一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...

  3. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

    一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...

  4. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)

    一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...

  5. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版

    package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...

  6. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)

    一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...

  7. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)

    一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...

  8. 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

    1. package algorithms.stacks13; /******************************************************************* ...

  9. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法

    1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...

随机推荐

  1. Ajax做无刷新三级联动

    1.引入JS and Jquery包 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " ...

  2. nginx负载均衡的简单实现

    负载均衡是我们大流量网站要做的一个东西,下面我来给大家介绍在Nginx服务器上进行负载均衡配置方法,希望对有需要的同学有所帮助哦. 负载均衡 先来简单了解一下什么是负载均衡,单从字面上的意思来理解就可 ...

  3. git常用命令收藏

    git init //初始化本地git环境 git clone XXX//克隆一份代码到本地仓库 git pull //把远程库的代码更新到工作台 git pull --rebase origin m ...

  4. 463. Island Perimeter Add to List

    You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represen ...

  5. .net core结合Consul集群&Docker实现服务治理

    实战中的asp.net core结合Consul集群&Docker实现服务治理 https://www.cnblogs.com/guolianyu/p/9614050.html 0.目录 整体 ...

  6. Til the Cows Come Home (最短路模板题)

    个人心得:模板题,不过还是找到了很多问题,真的是头痛,为什么用dijkstra算法book[1]=1就错了..... 纠结中.... Bessie is out in the field and wa ...

  7. 前端项目使用module.exports文件一定要Webpack编译吗?请问gulp可以编译这种文件吗

    import引入类似这种文件,一定要用webpack去编译吗 module.pxports 是CMD规范的一个全局函数,功能是当前模块对外提供接口.require可以直接使用这个接口.例子: echo ...

  8. Linux动态gif图的录制

    Linux动态gif图的录制 Linux动态gif图的录制 byzanz的安装与使用 recordmydesktop再convert成gif 参考资料 前几天写了两篇博客vim的配置和Vim的自动代码 ...

  9. bzoj 3771 Triple——FFT

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3771 把方案作为系数.值作为指数,两项相乘就是系数相乘.指数相加,符合意义. 考虑去重.先自 ...

  10. IIS:template

    ylbtech-IIS: 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   7.返回顶部   8.返回顶部   9.返回顶部   10.返 ...