1.

 package algorithms.util;

 import algorithms.ADT.Stack;

 /******************************************************************************
* Compilation: javac Evaluate.java
* Execution: java Evaluate
* Dependencies: Stack.java
*
* Evaluates (fully parenthesized) arithmetic expressions using
* Dijkstra's two-stack algorithm.
*
* % java Evaluate
* ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
* 101.0
*
* % java Evaulate
* ( ( 1 + sqrt ( 5 ) ) / 2.0 )
* 1.618033988749895
*
*
* Note: the operators, operands, and parentheses must be
* separated by whitespace. Also, each operation must
* be enclosed in parentheses. For example, you must write
* ( 1 + ( 2 + 3 ) ) instead of ( 1 + 2 + 3 ).
* See EvaluateDeluxe.java for a fancier version.
*
*
* Remarkably, Dijkstra's algorithm computes the same
* answer if we put each operator *after* its two operands
* instead of *between* them.
*
* % java Evaluate
* ( 1 ( ( 2 3 + ) ( 4 5 * ) * ) + )
* 101.0
*
* Moreover, in such expressions, all parentheses are redundant!
* Removing them yields an expression known as a postfix expression.
* 1 2 3 + 4 5 * * +
*
*
******************************************************************************/ public class Evaluate {
public static void main(String[] args) {
Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty()) {
String s = StdIn.readString();
if (s.equals("(")) ;
else if (s.equals("+")) ops.push(s);
else if (s.equals("-")) ops.push(s);
else if (s.equals("*")) ops.push(s);
else if (s.equals("/")) ops.push(s);
else if (s.equals("sqrt")) ops.push(s);
else if (s.equals(")")) {
String op = ops.pop();
double v = vals.pop();
if (op.equals("+")) v = vals.pop() + v;
else if (op.equals("-")) v = vals.pop() - v;
else if (op.equals("*")) v = vals.pop() * v;
else if (op.equals("/")) v = vals.pop() / v;
else if (op.equals("sqrt")) v = Math.sqrt(v);
vals.push(v);
}
else vals.push(Double.parseDouble(s));
}
StdOut.println(vals.pop());
}
}

最新文章

  1. 企业IT架构介绍
  2. node项目换了环境node_modules各种报错
  3. grunt 使用
  4. Xamarin基础命名空间Microsoft.SqlServer.Server
  5. Junit单元测试学习笔记二
  6. spring注入Properties
  7. 【Chromium中文文档】沙箱FAQ
  8. 资金平台交易明细扩展开发-DEP
  9. C语言---字符数组
  10. IAR中如何定向把数组和函数放在指定的地址单元
  11. surging+CentOS7+docker+rancher2.0 入门部署教程
  12. laravel 5.4 fopen(): Filename cannot be empty
  13. static的含义
  14. 注册登录二合一之bootstrap
  15. jdk安装和环境配置
  16. Loj 10211 sumdiv
  17. python常用运维脚本实例
  18. mysql安装错误解决办法
  19. Linux操作系统Vim代码Tab自动补全配置
  20. Hive可视化工具

热门文章

  1. Log4j_学习_03_自己动手封装log工具
  2. CentOS 6.8安装Docker V1.0
  3. 一段tcl代码
  4. freemarker实现第一个HelloWorld
  5. Mybatis中对于标签的配置可能不会出现自动提示解决方案
  6. 《Javascript高级程序设计》阅读记录(六):第六章 下
  7. php写入数据到mysql数据库中出现乱码解决方法
  8. ADMEMS软件架构的4个阶段
  9. 洛谷【AT2827】LIS
  10. Poj 2387 Til the Cows Come Home(Dijkstra 最短路径)