算术表达式的转换
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
Input
输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)
Output
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。
Sample Input
a*b+(c-d/e)*f#
Sample Output
+*ab*-c/def a*b+c-d/e*f ab*cde/-f*+
直接贴链接吧。
这老哥是用树来存的,然后用遍历来实现。这道题也可以用栈做(我真是不想写。。。太长了)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
char ch;
struct node *l,*r;
};
char s[110],s1[110],s2[110];
int q;
void post()
{
int x = 0, y = 0;
for(q = 0; s[q] != '#'; q++)
{
if(s[q] >= 'a' && s[q] <= 'z')
s1[x++] = s[q];
else if(s[q] == '(')
s2[y++] = s[q];
else if(s[q] == ')')
{
while(s2[y-1] != '(')
{
s1[x] = s2[y-1];
x++;
y--;
}
y--;
}
else if(s[q] == '+' || s[q] == '-')
{
while(y != 0 && s2[y-1] != '(')
{
s1[x] = s2[y-1];
x++;
y--;
}
s2[y++] = s[q];
}
else if(s[q] == '*' || s[q] == '/')
{
while(y != 0 &&(s2[y-1]=='*'||s2[y-1]=='/'))
{
s1[x] = s2[y-1];
x++;
y--;
}
s2[y++] = s[q];
}
}
while(y != 0)
{
s1[x] = s2[y-1];
x++;
y--;
}
s1[x] = '\0';
}
void preorder(struct node *p)
{
if(p == NULL)
return;
printf("%c",p->ch);
preorder(p->l);
preorder(p->r);
}
void inorder(struct node *p)
{
if(p == NULL)
return;
inorder(p->l);
printf("%c",p->ch);
inorder(p->r);
}
void postorder(struct node *p)
{
if(p == NULL)
return;
postorder(p->l);
postorder(p->r);
printf("%c",p->ch);
}
int main()
{
int i,top = 0;
scanf("%s",s);
//转化为后缀式
post();
//转化成表达式树(链栈)
struct node *po[110] = {NULL},*pi;
for(i = 0; i < q; i++)
{
if(s1[i] >= 'a' && s1[i] <= 'z')
{
pi = (struct node *)malloc(sizeof(struct node));
pi->ch = s1[i];
pi->l = NULL;
pi->r = NULL;
po[top++] = pi;
}
else
{
pi = (struct node *)malloc(sizeof(struct node));
pi->ch = s1[i];
pi->r = po[top-1];//注意先是右子树再是左子树
top--;
pi->l = po[top-1];
top--;
po[top++] = pi;
}
}
//分别遍历
preorder(po[0]);
printf("\n");
inorder(po[0]);
printf("\n");
postorder(po[0]);
printf("\n");
return 0;
}