算术表达式的转换
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*+
Hint
Source
前缀规律:
1) 设立操作符栈s,结果栈x;
2) 从右向左遍历,若当前字符是操作数,则直接发送给s;
3) 若当前运算符的优先数高于等于栈顶运算符,则进x栈;
4) 否则,退出栈顶运算符发送给x栈;
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char s[100005];
void hou(char st[], int l)
{
int i;
int top = 0;
for(i = 0; i < l; i++)
{
if(st[i] >= 'a' && st[i] <= 'z')
{
printf("%c", st[i]);
}
else if(st[i] == '(')
{
s[++top] = st[i];
}
else if(st[i] == ')')
{
for(; s[top] != '('; top--)
{
printf("%c", s[top]);
}
top--;
}
else if(st[i] == '+' || st[i] == '-')
{
while(1)
{
if(top == 0 || s[top] == '(')
{
s[++top] = st[i];
break;
}
printf("%c", s[top--]);
}
}
else if(st[i] == '*' || st[i] == '/')
{
while(1)
{
if(top == 0 || s[top] == '(' || s[top] == '+' || s[top] == '-')
{
s[++top] = st[i];
break;
}
printf("%c", s[top--]);
}
}
else if(st[i] == '#')
break;
}
for(;top > 0; top--)
printf("%c", s[top]);
}
void zhong(char st[], int l)
{
int i;
for(i=0;st[i]!='#';i++)
{
if(st[i]!='('&&st[i]!=')')
printf("%c",st[i]);
}
}
void qian(char st[], int l)
{
int i, j;
int top = 0;
j = 0;
char x[100005];
for(i = l - 2; i >= 0; i--)
{
if(st[i] >= 'a' && st[i] <= 'z')
x[++j] = st[i];
else if(st[i] == ')')
s[++top] = st[i];
else if(st[i] == '(')
{
for(; s[top] != ')'; top--)
{
x[++j] = s[top];
}
top--;
}
else if(st[i] == '+' || st[i] == '-')
{
while(1)
{
if(top == 0 || s[top] == ')'||s[top]=='+'||s[top]=='-')
{
s[++top] = st[i];
break;
}
x[++j] = s[top--];
}
}
else if(st[i] == '*' || st[i] == '/')
{
s[++top] = st[i];
}
}
for(; top > 0; top--)
x[++j] = s[top];
for(i = j; i > 0; i--)
printf("%c", x[i]);
}
int main()
{
char st[100005];
int l;
scanf("%s", st);
l = strlen(st);
qian(st, l);
printf("\n");
zhong(st, l);
printf("\n");
hou(st, l);
return 0;
}