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

  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 }
时间: 2024-09-30 17:47:24

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

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

一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归,因为递归代码比相应的非递归代码更加简洁优雅.易懂.下面这种实现中的注释就言简意赅地说明了代码的作用.我们可以用数学归纳法证明这段注释所解释的算法的正确性.我们会在 3.1 节中展开这个话题并为二分查找提供一个这样的证明.编写递归代码时最重要的有以下三点.? 递归总有一个最简单的情况——方法的第一条语

算法Sedgewick第四版-第1章基础-008一用数组实现固定长度的栈

1 package algorithms.ADT; 2 3 /****************************************************************************** 4 * Compilation: javac FixedCapacityStackOfStrings.java 5 * Execution: java FixedCapacityStackOfStrings 6 * Dependencies: StdIn.java StdOut.

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

1. 1 package algorithms.analysis14; 2 3 import algorithms.util.StdOut; 4 import algorithms.util.StdRandom; 5 6 /****************************************************************************** 7 * Compilation: javac DoublingTest.java 8 * Execution: jav

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

一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 1 package algorithms.elementary21; 2 3 /****************************************************************************** 4 * Compilation: javac Insertion.java 5 * Execution: java I

算法Sedgewick第四版-第1章基础-018一解决不能声明泛型数组的两咱方法(强转或反射)

1. 1 /****************************************************************************** 2 * Compilation: javac ResizingArrayStackWithReflection.java 3 * Execution: java ResizingArrayStackWithReflection < input.txt 4 * Dependencies: StdIn.java StdOut.jav

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

一. 1. 2. 3. 二.代码 1 package algorithms.mergesort22; 2 3 import algorithms.util.StdIn; 4 import algorithms.util.StdOut; 5 6 /****************************************************************************** 7 * Compilation: javac MergeBU.java 8 * Executio

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

1. package algorithms.stacks13; /****************************************************************************** * Compilation: javac ResizingArrayBag.java * Execution: java ResizingArrayBag * Dependencies: StdIn.java StdOut.java * * Bag implementatio

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

一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursively), and then merge the results. As you will see, one of mergesort’s most attractive properties is that it guarantees to sort any array of N items in t

算法Sedgewick第四版-第1章基础-003一封装交易对象

1. 1 package ADT; 2 3 /****************************************************************************** 4 * Compilation: javac Transaction.java 5 * Execution: java Transaction 6 * Dependencies: StdOut.java 7 * 8 * Data type for commercial transactions.