算术表达式的转换
Problem Description
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
Input
输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)
Output
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
+*ab*-c/def a*b+c-d/e*f ab*cde/-f*+
代码如下:
#include<stdio.h>
#include<string.h>
char x,a[111],b[111],ar[111];
int i,top=0;
int f1(char x)
{
if(x=='+'||x=='-') return 1;
else if (x=='/'||x=='*') return 2;
else if(x=='(') return 3;
else if(x==')') return 4;
else return 0;
}
int f2(char x)
{
if(x=='+'||x=='-') return 1;
else if (x=='/'||x=='*') return 2;
else if(x=='(') return 4;
else if(x==')') return 3;
else return 0;
}
void qian(char *b)
{
int ls=(int)strlen(b);
int q=0;
top=0;
for (i=ls-2; i>=0; i--)
{
if(b[i]>='a'&&b[i]<='z')
a[++q]=b[i];
else
{
if(top==0)
ar[++top] = b[i] ;
else if(f2(b[i])>=f2(ar[top]))
{
if(f2(b[i])==4)
{
while(ar[top]!=')')
a[++q]=ar[top--];
top-- ;
}
else
ar[++top] = b[i] ;
}
else
{
if(ar[top]!=')')
{
a[++q]=ar[top];
ar[top] = b[i] ;
}
else
ar[++top] = b[i];
}
}
}
while(top)
a[++q]=ar[top--] ;
while(q)
printf("%c",a[q--]);
printf("\n") ;
}
void zhong(char *b)
{
for(i=0; b[i]!='#'; i++)
{
x=b[i];
if (x!= '(' && x!= ')')
printf("%c", x);
}
printf("\n");
}
void hou(char *b)
{
for(i=0; b[i]!='#'; i++)
{
x=b[i];
if(x>='a'&&x<='z') printf("%c",x);
else
{
if(top==0) a[++top]=x;
else if(f1(x)>f1(a[top]))
{
if(x==')')
{
while(a[top]!='(')
{
printf("%c",a[top--]);
}
top--;
}
else a[++top]=x;
}
else
{
if(a[top]!='(')
{
printf("%c",a[top]);
a[top]=x;
}
else a[++top]=x;
}
}
}
while(top)
{
printf("%c",a[top--]);
}
printf("\n");
}
int main()
{
while(~scanf("%s",b))
{
qian(b);
zhong(b);
hou(b);
}
return 0;
}