中缀式变后缀式

2015-01-25 11:40:11 · 作者: · 浏览: 5

中缀式变后缀式

时间限制: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 / =
代码:
#include
      
       
int main()
{
	int T,i,top;
	char str[1005],ch[1005];
	scanf("%d",&T);
	while(T--)
	{
		scanf("%s",str);
		top=-1;
		for(i=0;str[i]!='\0';i++)
		{
			if(str[i]>='0'&&str[i]<='9')
			{
				while((str[i]=='.')||(str[i]>='0'&&str[i]<='9'))
				{
					printf("%c",str[i]);
					i++;
				}
				printf(" ");
			}
			if(str[i]=='=')
				break;
			if(str[i]==')')
			{
				while(top>=0&&(ch[top]!='('))
				{
					printf("%c ",ch[top]);
					top--;
				}
				top--;
			}
			else if(str[i]=='(')
			{
				top++;
				ch[top]=str[i];
			}
			else if(str[i]=='*'||str[i]=='/')
			{
				while((ch[top]=='*')||(ch[top]=='/'))
				{
					printf("%c ",ch[top]);
					top--;
				}
				top++;
				ch[top]=str[i];
			}
			else
			{
				while(top>=0&&(ch[top]!='('))
				{
					printf("%c ",ch[top]);
					top--;
				}
				top++;
				ch[top]=str[i];
			}
		}
		while(top>=0)
		{
			printf("%c ",ch[top]);
			top--;
		}
		printf("=\n");
	}
	return 0;
}

      
<script type="text/java script">
<script type="text/java script">BAIDU_CLB_fillSlot("771048");
点击复制链接 与好友分享! 回本站首页
<script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
您对本文章有什么意见或着疑问吗?请到 论坛讨论您的关注和建议是我们前行的参考和动力??
上一篇: 算法学习 - 链表之归并排序_O(1)空间_O(NlogN)时间_C++
下一篇: C++11初窥二: 继承构造函数和委派构造函数
相关文章
<script type="text/java script">BAIDU_CLB_fillSlot("182716");
<script type="text/java script">BAIDU_CLB_fillSlot("517916");
图文推荐
<iframe src="http://www.2cto.com/uapi.php?tid=360474&catid=339&title=1tDXusq9seS689e6yr0=&forward=http://www.2cto.com/kf/201412/360474.html" width="100%" height="100%" id="comment_iframe" name="comment_iframe" frameborder="0" scrolling="no">
<script type="text/java script">BAIDU_CLB_fillSlot("771057");