算术表达式的转换
Time Limit: 1000MS Memory limit: 65536K
题目描述
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
输入
输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)
输出
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
+*ab*-c/def a*b+c-d/e*f ab*cde/-f*+
#include <stdio.h> #include <string.h> char s[1010]; int top; void push(char n); int pop(); int empty(); void qian(char *str); void zhong(char *str); void hou(char *c); int main() { char str[1010]; while(gets(str)!=NULL) { qian(str); zhong(str); hou(str); } } void qian(char *str) { int l,i,j,k; char c[1100],tr[1010]; top=-1; l=strlen(str); for(i=l-2,j=0; i>=0; i--) { c[j++]=str[i]; } c[j]='#'; for(i=0,k=0; i<j+1; i++) { if(c[i]>='a'&&c[i]<='z')//if(c[i]!='*'&&c[i]!='+'&&c[i]!='-'&&c[i]!='/'&&c[i]!='('&&c[i]!=')'&&c[i]!='#') //å�¤æ�å�符æ�¯ä¸�æ�¯è¿�ç®�符 ä¸�æ�¯å°±è¾�å�º { tr[k++]=c[i]; } if(c[i]==')') push(c[i]); if(c[i]=='(') { while(s[top]!=')') if(!empty()) tr[k++]= pop(); pop(); } if(c[i]=='*'||c[i]=='/') push(c[i]); if(c[i]=='+'||c[i]=='-') { while(s[top]=='*'||s[top]=='/') { tr[k++]=pop(); } push(c[i]); } if(c[i]=='#') { while(!empty()) tr[k++]=pop(); break; } } for(i=k-1; i>=0; i--) printf("%c",tr[i]); printf("\n"); } void hou(char *c) { int l,i; top=-1; l=strlen(c); for(i=0;i<l;i++) { if(c[i]>='a'&&c[i]<='z')//å�¤æ�å�符æ�¯ä¸�æ�¯è¿�ç®�符 ä¸�æ�¯å°±è¾�å�º { printf("%c", c[i]) ; } if(c[i]=='(') push(c[i]); if(c[i]==')') { while(s[top]!='(') if(!empty()) printf("%c", pop()); pop(); } if(c[i]=='*'||c[i]=='/') push(c[i]); if(c[i]=='+'||c[i]=='-') { while(s[top]!='('&&s[top]!=')'&&!empty()) { printf("%c",pop()); } push(c[i]); } if(c[i]=='#') { while(!empty()) printf("%c",pop()); break; } } printf("\n"); } void zhong(char *s) { int l=strlen(s),i; for(i=0;i<l;i++) { if(s[i]!='('&&s[i]!=')'&&s[i]!='#') { printf("%c",s[i]); } } printf("\n"); } void push(char n) { s[++top]=n; } int pop() { return s[top--]; } int empty() { return top==-1; }