和上午写的那道题基本一样,不同的是,这道题是实数,所以处理数的时候遇到了点问题,刚开始一直想不出来怎么处理,后来和rihkddd打了会乒乓球,回来后立马就想明白了。。。题目:
中缀式变后缀式
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
-
输入
-
第一行输入一个整数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 / =
-
第一行输入一个整数n,共有n组测试数据(n<10)。
#include <iostream>
#include <cstdio>
#include <string.h>
#include <string>
#include <stack>
using namespace std;
struct oper{
char op;
int level;
}p;
int fun(char cc){
if(cc=='+'||cc=='-')
return 1;
else if(cc=='*'||cc=='/')
return 2;
else if(cc=='(')
return 3;
else if(cc==')')
return 0;
}
int main(){
//freopen("11.txt","r",stdin);
int numcase;
string str;
scanf("%d",&numcase);
while(numcase--){
cin>>str;
int len=str.size(),pos=0,ll=0;
double num=0;
char ch;
stack<oper> ss;
p.op=' ';p.level=0;ss.push(p);
while(pos<len-1){
if(str[pos]<='9'&&str[pos]>='0'){
while((str[pos]<='9'&&str[pos]>='0')||(str[pos]=='.')){
printf("%c",str[pos]);
pos++;
}
printf(" ");
}
else{
sscanf(&str[pos],"%c%n",&ch,&ll);
pos+=ll;p.op=ch;p.level=fun(ch);
if(p.op==')'){
while(ss.top().op!='('){
printf("%c ",ss.top().op);
ss.pop();
}
ss.pop();
}
else if(p.level>ss.top().level||ss.top().op=='(')
ss.push(p);
else{
while(p.level<=ss.top().level&&ss.top().op!='('){
printf("%c ",ss.top().op);
ss.pop();
}
ss.push(p);
}
}
}
while(!ss.empty()){
if(ss.top().op==' '){ss.pop();}
else{
printf("%c ",ss.top().op);
ss.pop();
}
}
printf("=\n");
}
return 0;
}