中缀式 前缀式 后缀式 转换
2017-10-23 22:17
316 查看
算术表达式的转换
Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic
Discuss
Problem Description
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
Input
输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)Output
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。Example Input
a*b+(c-d/e)*f#
Example Output
+*ab*-c/def a*b+c-d/e*f ab*cde/-f*+
Hint
#include<iostream> #include<string.h> using namespace std; char b[100010], s[100010] , print[100010]; int swi(char c)//前缀式优先级 { if(c=='+'||c=='-') return 1; if(c=='*'||c=='/') return 2; if(c==')') return 3; if(c=='(') return 4; return 0; } int swa(char c)//后缀式优先级 { if(c=='+'||c=='-') return 1; if(c=='*'||c=='/') return 2; if(c=='(') return 3; if(c==')') return 4; return 0; } void display(int k) { for(int i = k;i>0;i--) cout << print[i]; cout << endl; } //逆序读取数组,存入输出数组,再逆序输出 void qian(int n) { memset(s,0,sizeof(s[0])); memset(print,0,sizeof(print[0])); char c; int i ,k = 0, top = 0; for(i = n;i>0;i--)//逆读取 { c = b[i]; if(c>='a' && c<='z') print[++k] = c; else if(c != '(') { if(c == ')') s[++top] = c; else { while(top!=0&&s[top]!=')'&& swi(s[top]) > swi(c)) { print[++k] = s[top]; top--; } s[++top] = c; } } else { while(s[top]!= ')') { print[++k] = s[top]; top--; } top--; } } if(top!=0) { while(top) print[++k] = s[top--]; } display(k); } void hou(int n) { char c; int top = 0; memset(s,0,sizeof(s[0])); for(int i = 1;i<=n;i++) { c = b[i]; if(c>='a' && c<='z') cout << c; else { if(top==0) s[++top] = c; else if(swa(c) <= swa(s[top])) { if(s[top] == '(') s[++top] = c; else { cout << s[top]; s[top] = c; } } else { if(c==')') { while(s[top]!='(') { cout << s[top]; top--; } top--; } else s[++top] = c; } } } if(top!=0) { while(top!=0) cout << s[top--]; } cout << endl; } int main() { char c; int n = 0; while(cin >> c &&c!='#') b[++n] = c;//存入数组中 qian(n); for(int i = 1;i<=n;i++) { if(b[i]!='('&&b[i]!=')') cout << b[i]; } cout << endl; hou(n); return 0; }
相关文章推荐
- 前缀式、中缀式、后缀式相互转换
- 表达式的中缀式转换为前缀式及后缀式
- 数据结构实验之栈二:一般算术表达式转换成前缀式,中缀式,后缀式
- 中缀式转换为后缀式(逆波兰式)方法
- 栈及实现(C语言)以及中缀式到后缀式的转换实例
- 表达式求值 中缀式转换成后缀式
- 中缀式转换为后缀式(逆波兰式)方法
- 中缀式转化为前缀式,中缀式转化为后缀式
- nyoj-409 郁闷的C小加(三) (表达式求值,中缀式转前缀式,中缀式转后缀式)
- 如何将中缀式转化成前缀式和后缀式
- 中缀式转换为后缀式(逆波兰式)方法
- 前缀式(波兰式)与后缀式(逆波兰式)求解表达式的值,中缀式(一般算数表达式不做讨论)
- 中缀式转换为后缀式(逆波兰式)方法
- 顺序栈应用2(利用顺序栈将中缀式转换成前、后缀式并求值)
- 如何推倒后缀式(如何由中缀式转换为后缀式)
- 手工转换中缀式与前、后缀式(转)
- 如何将中缀式转化成前缀式和后缀式(波兰和逆波兰)(适合考试使用的简单办法)
- 如何将中缀式转化成前缀式和后缀式
- 中缀式转前缀式:转后缀式
- 如何将中缀式转化成前缀式和后缀式(波兰和逆波兰)结合二叉树(适合数据结构方面的理解)