算术表达式的转换
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 <stdlib.h> #include <string.h> #define maxsize 10000 typedef char element; typedef struct { element *top,*base; int sizestack; } Sq; int init(Sq &L) { L.base=new element; if(!L.base) exit(-1); L.top=L.base; L.sizestack=maxsize; return 0; } int isempty(Sq &L) { if(L.top<=L.base) return 1; else return 0; } int isfull(Sq &L) { if(L.top-L.base>L.sizestack-1) return 1; else return 0; } int getto(Sq &L) { int e; if(isempty(L)==1) return 0; return e=*(L.top); } int push(Sq &L,char t) { if(isfull(L)==1) return 0; *(++L.top)=t; return 0; } int pop(Sq &L) { if(isempty(L)==1) return 0; *(L.top--); return 0; } int main() { char a[1000]; Sq L; Sq S; int i; char e; gets(a); int n=strlen(a); ///****************前缀输出********************************* init(L); init(S); for(i=n-2; i>=0; i--) { ///如果遇到“ )”进L1栈; if(a[i]==')') push(L,a[i]); ///如果遇到“( ”,如果L1栈顶不是“ )”,L1的栈顶元素,进S1栈,出L1栈;直到遇到“( ”,出L1栈 else if(a[i]=='(') { while(*(L.top)!=')') { e=getto(L); push(S,e); pop(L); } pop(L); } ///如果遇到“*”或“/”;进L1栈; else if(a[i]=='*'||a[i]=='/') { push(L,a[i]); } ///如果遇到“+”或“-”,如果L1的栈顶元素是“*”或“/”,L1的栈顶元素进S1栈,出L1栈;“+”或“-”进L1栈; else if(a[i]=='+'||a[i]=='-') { while(*(L.top)=='*'||*(L.top)=='/') { e=getto(L); push(S,e); pop(L); } push(L,a[i]); } ///字母直接进S1栈; else { push(S,a[i]); } } while(isempty(L)!=1) { e=getto(L); pop(L); push(S,e); } while(isempty(S)!=1) { e=getto(S); printf("%c",e); pop(S); } printf("\n"); ///********************中缀输出**************************** for(i=0; i<n-1; i++) if(a[i]!='('&&a[i]!=')') printf("%c",a[i]); printf("\n"); ///*********************后缀输出******************************** init(L); for(i=0; a[i]!='#'; i++) { ///遇到左括弧一律入栈; if(a[i]=='(') push(L,a[i]); ///遇到右括弧就把两个括弧之间的所有符号出栈输出,并且左括弧出栈; else if(a[i]==')') { while(isempty(L)!=1&&*(L.top)!='(') { e=getto(L); printf("%c",e); pop(L); } pop(L); } ///遇到“*”或“/”,如果栈不空并且栈顶不是左括弧并且栈顶是“*”或“/”,就把栈顶出栈输出,“*”或“/”入栈; else if(a[i]=='*'||a[i]=='/') { if((isempty(L)!=1)&&*(L.top)=='('&&(*(L.top)=='*'||*(L.top)=='/')) { e=getto(L); printf("%c",e); pop(L); } push(L,a[i]); } ///遇到“+”或“-”,如果栈不空并且栈顶不是左括弧就出栈输出这一个栈顶,“+”或“-”入栈; else if(a[i]=='+'||a[i]=='-') { if(isempty(L)!=1&&*(L.top)!='(') { e=getto(L); printf("%c",e); pop(L); } push(L,a[i]); } ///遇到字母一律输出; else { printf("%c",a[i]); } } while(isempty(L)!=1) { e=getto(L); printf("%c",e); pop(L); } printf("\n"); return 0; }