NYOJ-467 中缀式变后缀式

中缀式变后缀式

时间限制: 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[N];
		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;
}        
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值