算法Sedgewick第四版-第1章基础-007一用两个栈实现简单的编译器
2024-08-30 16:42:18
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());
}
}
最新文章
- 企业IT架构介绍
- node项目换了环境node_modules各种报错
- grunt 使用
- Xamarin基础命名空间Microsoft.SqlServer.Server
- Junit单元测试学习笔记二
- spring注入Properties
- 【Chromium中文文档】沙箱FAQ
- 资金平台交易明细扩展开发-DEP
- C语言---字符数组
- IAR中如何定向把数组和函数放在指定的地址单元
- surging+CentOS7+docker+rancher2.0 入门部署教程
- laravel 5.4 fopen(): Filename cannot be empty
- static的含义
- 注册登录二合一之bootstrap
- jdk安装和环境配置
- Loj 10211 sumdiv
- python常用运维脚本实例
- mysql安装错误解决办法
- Linux操作系统Vim代码Tab自动补全配置
- Hive可视化工具