XYNUOJ 2018: 中缀式变后缀式

2018: 中缀式变后缀式

时间限制: 1 Sec  内存限制: 64 MB
提交: 14  解决: 11
您该题的状态:已完成
[提交][状态][讨论版]

题目描述

人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。

输入

第一行输入一个整数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 / =
#include<iostream>
#include<stack>
#include<string>
using namespace std;
string s,str;
int yxj(char ch)
{
	switch(ch)//判断运算符的优先级
	{
		case'+':
		case'-':
			return 1;
		case'*':
		case'/':
			return 2;
		default:
			return 0;
	}
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		cin>>s;
		stack<char>pq;
		pq.push('#');
		int len=s.size(),i=0;
		str.clear();//将栈清空
		while(i<len-1)//把等于号先剔除,最后再加上
		{
			if(s[i]=='(')//如果碰到左括号,将其放入栈内
			{
				pq.push(s[i]);
				i++;
			}
			else if(s[i]==')')//碰到右括号时,将右括号到左括号内的数字输出,不输出左括号
			{
				while(pq.top() !='(')
				{
					str+=pq.top();
					pq.pop();
					str+=' ';
				}
				pq.pop();
				i++;
			}
			else if(s[i]=='+'||s[i]=='-'||s[i]=='*'|s[i]=='/')//当碰到运算符号的时候,按优先级存入栈中
			{
				while(yxj(pq.top())>=yxj(s[i]))
				{
					str+=pq.top();
					str+=' ';
					pq.pop();
				}
				pq.push(s[i]);
				i++;
			}
			else
			{
				while(s[i]>='0'&&s[i]<='9'||s[i]=='.')//碰到数字时,将数字输出
				{
					str+=s[i];
					i++;
				}
				str+=' ';
			}
		}
		while(pq.top()!='#')//将栈中剩余的东西掏空
		{
			str+=pq.top();
			pq.pop();
			str+=' ';
		}
		str+='=';//最后加上等于号
		cout<<str<<"\n";
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yxy602843889/article/details/81412130