博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Infix to Postfix Expression
阅读量:4945 次
发布时间:2019-06-11

本文共 2176 字,大约阅读时间需要 7 分钟。

Example : 

Infix : (A+B) * (C-D) )

Postfix: AB+CD-*

算法:

1. Scan the infix expression from left to right.

2. If the scanned character is an operand, append it to result.

3. Else

  3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.

  3.2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.)

4. If the scanned character is an ‘(‘, push it to the stack.

5. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the parenthesis.

6. Repeat steps 2-6 until infix expression is scanned. 

7. Append the remaing items int the stack.

public class InfoxToPostfix {    private int order(char ch) {        switch (ch) {        case '+':        case '-':            return 1;        case '*':        case '/':            return 2;        case '^':            return 3;        default:            return -1;        }    }    private String infixToPostfix(String exp) {        StringBuilder result = new StringBuilder();        Stack
stack = new Stack<>(); for (int i = 0; i < exp.length(); ++i) { char c = exp.charAt(i); if (Character.isLetterOrDigit(c)) { result.append(c); } else if (c == '(') { stack.push(c); } else if (c == ')') { while (!stack.isEmpty() && stack.peek() != '(') { result.append(stack.pop()); } stack.pop(); } else { while (!stack.isEmpty() && order(c) <= order(stack.peek())) { result.append(stack.pop()); } stack.push(c); } } while (!stack.isEmpty()) { result.append(stack.pop()); } return result.toString(); }}

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/11225354.html

你可能感兴趣的文章
Java消息服务
查看>>
Jtester使用
查看>>
详解CSS样式的position属性
查看>>
Python机器学习(5)——朴素贝叶斯分类器
查看>>
Mac 10.12连接iSCSI硬盘软件iSCSI Initiator X
查看>>
ffmpeg获取文件的总时长(mp3/mp4/flv等)
查看>>
Python virtualenvwrapper在Win下的安装和管理
查看>>
费马小定理
查看>>
mysql5.6 忘记root密码
查看>>
HTML 小练习(智联注册页)
查看>>
MSSQL优化之————探索MSSQL执行计划(转)
查看>>
使用DOS命令查找包含某一字符串的所有文件
查看>>
python强大的区间处理库interval用法介绍
查看>>
MVC开发中的常见错误-04-“System.NullReferenceException”类型的异常在 BBFJ.OA.WebApp.dll 中发生,但未在用户代码中进行处理...
查看>>
VS-常用的快捷键-总结
查看>>
如何在网页中用echarts图表插件做出静态呈现效果
查看>>
在Linux系统下挂载Windows上的共享文件夹
查看>>
【转】sizeof详解
查看>>
北京金隅男篮夺冠
查看>>
SQL SERVER-2008从入门到精通pdf
查看>>