您的位置:首页 > 其它

NYOJ-467 中缀式变后缀式

2013-10-30 21:59 190 查看


中缀式变后缀式

时间限制: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 <string.h>
#include <ctype.h>
#include <stack>

#define N 1005

using namespace std;

stack<char>q;

int main()
{
int k;
scanf("%d", &k);
while(k --){
char a
;
scanf("%s", a);
int len = strlen(a);
for(int i = 0; i < len; i ++){
if(isdigit(a[i]) || a[i] == '.'){
printf("%c", a[i]);
continue;
}
if(a[i] == '('){
q.push(a[i]);
continue;
}
if(a[i] == ')'){
while(q.top() != '('){
printf(" %c", q.top());
q.pop();
}
q.pop();
continue;
}
if(q.empty()){
printf(" ");
q.push(a[i]);
continue;
}
if(a[i] == '+' || a[i] == '-'){
printf(" ");
while(!q.empty() && q.top() != '('){
printf("%c ", q.top());
q.pop();
}
q.push(a[i]);
}
if(a[i] == '*' || a[i] == '/'){
printf(" ");
while(!q.empty() && (q.top() == '*' || q.top() == '/')){
printf("%c ", q.top());
q.pop();
}
q.push(a[i]);
}
if(a[i] == '='){
while(!q.empty()){
printf(" %c", q.top());
q.pop();
}
printf(" =\n");
}
}
}

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