中序表达式 to 后序表达式
来源:互联网 发布:ubuntu编译配置lnmp 编辑:程序博客网 时间:2024/05/16 10:59
将带有计算的优先级和括号的中序表达式变成符合某文法的后序表达式。
- 《编程导论(Java)·5.5.2》的参考资料
- 解释器模式中或许需要的工具
直接上代码。
package intent.interpreter.calculator2;import java.util.HashMap;import java.util.Stack;import tool.God;public class Nothing{ private static HashMap<Character,Integer> priority=new HashMap<Character,Integer>(){ { put('+', 1); put('-', 1); put('/', 2); put('*', 2); put('(', 0); } }; /** * 将带有计算的优先级和括号的中序表达式inOrder变成符合前述文法的后序表达式 */ static String inToPost(String inOrder) { Stack<Character> s = new Stack<>(); String res = "";//postfix expression char temp ;//保存s.pop() char[] expr = inOrder.trim().toCharArray(); for (char x :expr) { //如果是操作数,直接输出 if ( !isOperator(x) && ( x!='(' ) && ( x!=')') ) { res = res + x; }else if (x=='(') { s.push(x);//入栈 }else if (x==')') {//输出栈中的右操作符直到取出(。 temp = s.pop(); while (temp!='(') { res = res + temp; temp = s.pop(); } temp = '\0'; }else if (isOperator(x)) {//与栈顶操作符比较优先级 if (!s.isEmpty()) { temp = s.pop(); int prio1 = priority.get(temp); int prio2 = priority.get(x); while ( prio1 >= prio2 ) { res = res + temp; prio1 = -1; if (!s.isEmpty()) { temp = s.pop(); prio1 = priority.get(temp); } } if ((prio1 < prio2) && (prio1 != -1)){ s.push(temp); } } s.push(x); } }// end for while (!s.isEmpty() ) { temp = s.pop(); res = res + temp; } return res; } static boolean isOperator(char c) { return c=='+'||c=='-'||c=='*'||c=='/'; } static void test(){ String inOrder = "a+b*c-d"; inOrder= (String)God.getValue("expression"); System.out.println(" inOrder = "+inOrder); System.out.println(" postOrder = "+inToPost(inOrder)); }}inOrder = a+b*c-d
postOrder = abc*+d-
inOrder = (a+b)*(c-d)
postOrder = ab+cd-*
inOrder = a+b/c*(c-d)
postOrder = abc/cd-*+
使用配置文件时:
#intent.interpreter.calculator2. Alph ={a|b|c|d}.Op={*|+|-}
#expression = (a+b)*(c-d)
#expression =a+b*c-d
expression = a+b/c*(c-d)
0 0
- 中序表达式 to 后序表达式
- 中序表达式转换为后序表达式
- 中序表达式变成后序表达式 JAVA实现版本
- 前序、中序、后序表达式
- 前(中后)序表达式讲解
- “中序表达式”转换为“前序表达式”、“后序表达式”
- 中序表达式转成前序表达式和后序表达式及其计算方法
- “中序表达式”转换为“前序表达式”、“后序表达式”
- 将算术表达式由中序表达式转为后序表达式
- 1.3.10将算术表达式由中序表达式转为后序表达式(algs4)
- 将中序表达式转为后序表达式
- 中序表达式转后序表达式
- 前、中、后缀表达式和前、中、后序遍历
- 《算法(第四版)》 习题:1.3.10 将算术表达式由中序表达式转为后序表达式
- 中序表达式转后序表达式(带括号)
- 中序表达式转后缀表达式
- 中序表达式求值
- 中序表达式求值
- hdu 5007(字符串水题)
- 最长公共子序列(Longest Common Subsequence, LCS)
- Redis Sentinel:集群Failover解决方案
- 美国免投诉空间、外贸仿牌网站建设
- android ViewHolder优化
- 中序表达式 to 后序表达式
- poj-2591
- 影响CSS渲染速度的写法与建议
- LeetCode - Partition List
- [转载]ANDROID内存优化(大汇总——上)
- Mac OS X终端命令开启功能
- Qt编译过程中出现的问题
- js,jq清除360浏览器自动保存保单信息
- TCP