中缀表达式转为后缀表达式 ---- 栈
来源:互联网 发布:学生党淘宝店铺白菜价 编辑:程序博客网 时间:2024/05/18 00:06
题目:给一个中缀表达式(即标准形式的表达式),打印该表达式的后缀表达式。中缀表达式最大的不同就是去掉了表示运算符优先级的括号。操作数为26个小写或大写的英文字母(注意不包括数字和其他字符),操作符为+,-,*,/,(,),^,=,一共八个。具体见例子见下图 :
代码如下:
#include <iostream>#include <string>#include <stack>using namespace std;/* 判断字符ch是否是一个操作数 */bool IsOperand(char ch){ return (ch>='a' && ch<='z') || (ch>='A' && ch<='Z');}/* 返回操作数的等级 */int GetRange(char oper){ switch (oper) { case '+': case '-':return 0; case '^': case '*': case '/':return 1; case '(': case '#':return -1; }//凡是进栈的都要有等级}/* 把中缀转化为后缀并输出 */void InfixToPostfix(string str){ cout << str << "----> "; int len = str.size(); stack<char> s; s.push('#'); for (int i = 0; i < len; i++) { if (str[i] == '=') { while (s.top() != '#') { cout << s.top(); s.pop(); } cout << str[i]; } else if (IsOperand(str[i])) cout << str[i]; else { if (str[i] == '(') s.push(str[i]); else if (GetRange(str[i]) <= GetRange(s.top())) { while (GetRange(str[i]) <= GetRange(s.top())) { cout << s.top(); s.pop(); } s.push(str[i]); } else if (str[i] == ')') { while (s.top() != '(') { cout << s.top(); s.pop(); } s.pop();//删掉'(' } else s.push(str[i]); } }//for (int i = 0; i < len; i++) while (s.top() != '#') { cout << s.top(); s.pop(); } cout << endl;}int main(){ string str1 = "a+b*c+(d*e+f)*g"; string str2 = "X=A+B*(C-D)/E"; string str3 = "(a*b)^a=c^d"; InfixToPostfix(str1); InfixToPostfix(str2); InfixToPostfix(str3); return 0;}
数据测试在上图。
1 0
- 栈实现中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式 ---- 栈
- 中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式
- 中缀表达式转为后缀表达式(利用顺序栈实现)
- java将中缀表达式转为后缀表达式
- java 实现中缀表达式转为后缀表达式
- 中缀表达式如何转为后缀表达式
- 中缀表达式转为后缀表达式以及后缀表达式的计算
- 数据结构--中缀表达式转为后缀表达式(逆波兰表达式)
- 将中缀表达式转为后缀表达式和前缀表达式
- C# 堆栈例子--中缀表达式转为后缀表达式
- 【算法与数据结构】中缀表达式转为后缀表达式
- 逆波兰:将中缀表达式转为后缀表达式
- 使用基于ThinkPHP3.2.3的ThinkAdmin创建手机电脑通用的表白墙(七)优化:访问控制
- Apache solr和elastic search的比较
- CentOS中安装与配置Tomcat-8方法
- KMP算法详解
- PullToRefresh客户端和服务器端详解
- 中缀表达式转为后缀表达式 ---- 栈
- 在CentOS 7中安装Docker
- WM算法详解
- JAVA Executor实现并发线程
- dd备份系统和系统恢复
- 从JVM的角度看JAVA代码--代码优化
- android studio 第一天
- Android View 绘制流程 与invalidate 和postInvalidate 分析--从源码角度
- 软件测试的自我修养之学习自动化测试