您的位置:首页 > 其它

中缀式变后缀式

2017-08-10 10:36 260 查看


中缀式变后缀式

时间限制: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 / =


来源
数据结构
上传者

mix_math

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include <cstdlib>
#include<cctype>
using namespace std;

int check(char a){
if(a=='(')
return 0;
if(a==')')
return 3;
if(a=='+'||a=='-')

return 1;

if(a=='*'||a=='/')
return 2;
}
int main(){
int t;
scanf("%d",&t);

while(t--){

char str[1009]={0};
scanf("%s",str);

stack<char>st;
st.push('=');

for(int i=0;i<strlen(str)-1;i++)
{
if(isdigit(str[i]))
{
char a[1000]={0};
sscanf(str+i,"%[0-9.]",a);
printf("%s",a);
putchar(' ');
i+=strlen(a)-1;

}

else if(str[i]=='(')
st.push('(');

else if(str[i]==')')
{
while(st.top()!='('&&st.size()!=1)
{
printf("%c ",st.top());
st.pop();
}
st.pop();
}

else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
{
if(st.empty())
st.push(str[i]);
while(check(st.top())>=check(str[i])&&st.size()!=1)//不处理最后的等号
{
printf("%c ",st.top());
st.pop();
}
st.push(str[i]);
}

}

while(!st.empty()&&st.size()!=1)
{
printf("%c ",st.top());
st.pop();
}
printf("=\n");

}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  中缀转后缀