中缀式变后缀式
题目描述:
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入描述:
第一行输入一个整数n,共有n组测试数据(n<10)。 每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式的中缀式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出描述:
每组都输出该组中缀式相应的后缀式,要求相邻的操作数操作符用空格隔开。
样例输入:
2 1.000+2/4= ((1+2)*5+1)/4=
样例输出:
1.000 2 4 / + = 1 2 + 5 * 1 + 4 / =
这道题就是在‘郁闷的C小加(一)’的基础上输出加了个条件,要求相邻的操作数操作符用空格隔开,所以我在每个操作数的后面加了一个‘#’方便区分连在一起的操作数,具体实现看代码
代码:#include<stdio.h> #include<string.h> #include<algorithm> #include<iostream> #include<map> #include<queue> #include<stack> using namespace std; char x[10005]; map<char,int>mp; void init() { scanf("%s",x); int len=strlen(x); queue<char>s2; //存数字 stack<char>s1; //存符号 for(int i=0; i<len; i++) { if(x[i]>='0'&&x[i]<='9') { while(x[i]>='0'&&x[i]<='9'||x[i]=='.') { s2.push(x[i]); i++; } i--; s2.push('#'); } else { if(x[i]==')') { while(1) { char s=s1.top(); if(s=='(') break; s2.push(s); s1.pop(); } s1.pop(); } else if(x[i]=='('||s1.empty()) s1.push(x[i]); else { while(1) { if(s1.empty()) break; char s=s1.top(); if(mp[x[i]]>mp[s]||s1.empty()) break; s1.pop(); s2.push(s); } s1.push(x[i]); } } } while(!s1.empty()) { char s=s1.top(); s2.push(s); s1.pop(); } while(!s2.empty()) { if(s2.front()>='0'&&s2.front()<='9'||s2.front()=='.') printf("%c",s2.front()); else if(s2.front()=='#') printf(" "); else printf("%c ",s2.front()); s2.pop(); } printf("\n"); } int main() { mp['*']=mp['/']=2,mp['+']=mp['-']=1,mp['(']=0; int t; scanf("%d",&t); while(t--) { memset(x,0,sizeof(x)); init(); } return 0; }