pta 5-8 表达式转换 (25分) (栈)
2017-03-20 17:40
519 查看
5-8 表达式转换 (25分)
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
解题思路:
这题很坑,会出现小数什么的,然后每个数前面后有可能出现正负号,但是分析清楚了处理起来也还好。
代码:
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、
-、
*、
\以及左右括号
(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
解题思路:
这题很坑,会出现小数什么的,然后每个数前面后有可能出现正负号,但是分析清楚了处理起来也还好。
代码:
#include <bits/stdc++.h> using namespace std; char a[22]; char oper[22]; bool judge(char x) { return ((x<='9' && x>='0') || x=='.'); } int main() { scanf("%s", a); int i, j; char num[22]; int siz=0; int isfirst=1; int top=0; for(i=0; a[i]; i++) { if(judge(a[i])) { num[siz++]=a[i]; } else { if(siz>0) { if(isfirst){isfirst=0;} else printf(" "); for(j=0; j<siz; j++) { printf("%c", num[j]); } siz=0; } if( (a[i]=='-') && (i==0 || (i>0 && !judge(a[i-1])))) { if(a[i]=='-') num[siz++]=a[i]; continue; } if(a[i]=='+' && (i==0 || (i>0 && !judge(a[i-1]) && a[i-1]!=')'))) { continue; } if(a[i]=='-' || a[i]=='+') { // printf("\noper%c\n", oper[top]); while(top>0 && (oper[top]=='+' || oper[top]=='-' || oper[top]=='*' || oper[top]=='/')) { printf(" %c", oper[top--]); } oper[++top]=a[i]; } if(a[i]=='*' || a[i]=='/') { if(top>0 && ( oper[top]=='*' || oper[top]=='/'))printf(" %c", oper[top--]); oper[++top]=a[i]; } if(a[i]=='(') { oper[++top]=a[i]; } if(a[i]==')') { while(top>0 && oper[top]!='(') { printf(" %c", oper[top--]); } top--; } } } if(siz>0) { if(isfirst){isfirst=0;} else printf(" "); for(j=0; j<siz; j++) { printf("%c", num[j]); } siz=0; } for(i=top; i>0; i--)printf(" %c", oper[i]); }
相关文章推荐
- PTA 3.11表达式转换
- 5-2 表达式转换 (25分)
- PTA 表达式转换 算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
- 5-1 表达式转换 (25分)
- PTA-表达式转换
- 5-20 表达式转换 (25分)
- PTA 求前缀表达式的值 (25分)
- 5-20 表达式转换 (25分)
- 数据结构之栈----PTA题目7-20表达式转换(中缀转后缀)
- 5-20 表达式转换 (25分)
- PTA数据结构之表达式转换
- PTA 7-1 表达式转换——表达式树
- PTA 5-10 树的遍历 (25分)【已知后序和中序求树】
- JS中应用正则表达式转换大小写
- 前缀中缀后缀表达式及其互相转换
- Java实现-将普通表达式转换成逆波兰表达式并计算
- pta 5-3 红色警报 (25分) 并查集
- 将中缀表达式转换成后缀表达式的三种方 法
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈二:一般算术表达式转换成后缀式(栈)