/******************************************************************************
* Compilation: javac EvaluateDeluxe.java
* Execution: java EvaluateDeluxe
* Dependencies: Stack.java
*
* Evaluates arithmetic expressions using Dijkstra's two-stack algorithm.
* Handles the following binary operators: +, -, *, / and parentheses.
*
* % echo "3 + 5 * 6 - 7 * ( 8 + 5 )" | java EvaluateDeluxe
* -58.0
*
*
* Limitiations
* --------------
* - can easily add additional operators and precedence orders, but they
* must be left associative (exponentiation is right associative)
* - assumes whitespace between operators (including parentheses)
*
* Remarks
* --------------
* - can eliminate second phase if we enclose input expression
* in parentheses (and, then, could also remove the test
* for whether the operator stack is empty in the inner while loop)
* - see http://introcs.cs.princeton.edu/java/11precedence/ for
* operator precedence in Java
*
******************************************************************************/ import java.util.TreeMap; public class EvaluateDeluxe { // result of applying binary operator op to two operands val1 and val2
public static double eval(String op, double val1, double val2) {
if (op.equals("+")) return val1 + val2;
if (op.equals("-")) return val1 - val2;
if (op.equals("/")) return val1 / val2;
if (op.equals("*")) return val1 * val2;
throw new RuntimeException("Invalid operator");
} public static void main(String[] args) { // precedence order of operators
TreeMap<String, Integer> precedence = new TreeMap<String, Integer>();
precedence.put("(", 0); // for convenience with algorithm
precedence.put(")", 0);
precedence.put("+", 1); // + and - have lower precedence than * and /
precedence.put("-", 1);
precedence.put("*", 2);
precedence.put("/", 2); Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty()) { // read in next token (operator or value)
String s = StdIn.readString(); // token is a value
if (!precedence.containsKey(s)) {
vals.push(Double.parseDouble(s));
continue;
} // token is an operator
while (true) { // the last condition ensures that the operator with higher precedence is evaluated first
if (ops.isEmpty() || s.equals("(") || (precedence.get(s) > precedence.get(ops.peek()))) {
ops.push(s);
break;
} // evaluate expression
String op = ops.pop(); // but ignore left parentheses
if (op.equals("(")) {
assert s.equals(")");
break;
} // evaluate operator and two operands and push result onto value stack
else {
double val2 = vals.pop();
double val1 = vals.pop();
vals.push(eval(op, val1, val2));
}
}
} // finished parsing string - evaluate operator and operands remaining on two stacks
while (!ops.isEmpty()) {
String op = ops.pop();
double val2 = vals.pop();
double val1 = vals.pop();
vals.push(eval(op, val1, val2));
} // last value on stack is value of expression
StdOut.println(vals.pop());
assert vals.isEmpty();
assert ops.isEmpty();
}
}

算法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. MongoDB 高可用集群搭建(3.4)

      一.架构概况192.168.56.101192.168.56.102192.168.56.103OS为centos 7.2 架构图: 规划5个组件对应的端口号,由于每台机器均需要同时部署 mong ...

  2. angular复选框式js树形菜单(一)

    treeView.html <ul class="tree-view"> <li ng-repeat="item in treeData" n ...

  3. TreeView的用法总结

    1.循环往treeview中添加数据 public AuthorNavUserControl() { InitializeComponent(); LoadTrees(MainForm.Project ...

  4. MySQL相关日志介绍

    1.MySQL中主要日志如下: ① 错误日志(Log Error) ② 查询日志(Query Log) ③ 二进制日志(Binary Log) 2.相关日志的作用: 1) 错误日志(Error Log ...

  5. HQ的测试流程

    测试流程如下图:

  6. 设置SSH自动登陆(免密码,用户名)

    设置SSH自动登陆(免密码,用户名)   1.创建公钥.公钥  ssh-keygen -t rsa  无视它出来的任何提示,欢快的一路回车到底吧.  2.把公钥 id_rsa.pub 复制到远程机器的 ...

  7. CodeForces - 1025F:Disjoint Triangles (几何)

    A point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles a ...

  8. Eclipse中Maven配置操作

    1.修改为自己的maven路径 2.对应的自己的仓库设置

  9. 畅通工程(自己写的BFS,但后面想了下并查集更好更快)

    某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇.省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可). ...

  10. [Luogu3674]小清新人渣的本愿

    luogu 题意 给你一个序列a,长度为n,有m次操作,每次询问一个区间是否可以选出两个数它们的差为x,或者询问一个区间是否可以选出两个数它们的和为x,或者询问一个区间是否可以选出两个数它们的乘积为x ...