中缀式变后缀式
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");
}
}
相关文章推荐
- 手工转换中缀式与前、后缀式
- 表达式的中缀式转换为前缀式及后缀式
- 栈及实现(C语言)以及中缀式到后缀式的转换实例
- 后缀式与中缀式的恩怨-->中缀表达式转化为后缀表达式
- 中缀式与后缀式的转化 郁闷的C小加(一)
- 前缀式(波兰式)与后缀式(逆波兰式)求解表达式的值,中缀式(一般算数表达式不做讨论)
- 算法题:四则运算(中缀式到后缀式的转换,值得思考的逆波兰式)
- 表达式求值 中缀式转换成后缀式
- 中缀式转换为后缀式(逆波兰式)方法
- nyoj 467 中缀式变后缀式 nyoj 257 郁闷的C小加(一)
- 中缀式转化为后缀式的步骤 (简单计算器 的实现)
- NYOJ467 中缀式转后缀式 java
- 中缀式转换为后缀式(逆波兰式)方法
- 由中缀式转化为后缀式
- 用二叉树实现表达式中缀式变后缀式并求值
- 中缀式转前缀式:转后缀式
- nyoj 1272 表达式求值(中缀式转后缀式)
- 如何将中缀式转化成前缀式和后缀式(波兰和逆波兰)(适合考试使用的简单办法)
- 后缀式中中缀式
- 顺序栈应用2(利用顺序栈将中缀式转换成前、后缀式并求值)