120 likes | 133 Views
Learn how to convert infix to postfix expressions using a stack-based algorithm in C language.
E N D
中缀表达式变后缀表达式算法 • Int postfix(qstype *s,char *expression) • { • char x1,x2,x; • int j=0; • s-->stack[0]=‘#’; • s-->top=0; • x2=expression[j];
If((x1=gettopqstack(s))==NIL) • exit(0); • while(1) • { • if(x2!=‘+’&& x2!=‘-’&& x2!=‘*’&& x2!=‘/’&& x2!=‘(‘ && x2!=‘)’ && x2!=‘#’) • { printf(“% c”,x2); • x2=expression[++j]; • }
else if(proceed(x1,x2)==‘<‘) • { if(!pushqstack(s,x2)) • exit(0); • if((x1=gettopqstack(s))==NIL) • exit(0); • x2= expression[++j]; • } • else if(proceed(x1,x2)==‘>‘) • { if((x=popqstack(s))==NIL) • exit(0);
printf(“% c”,x); • if((x1=gettopqstack(s))==NIL) • exit(0); • } • else if(proceed(x1,x2)==‘=‘&& x1=‘(‘ && x2=‘)’) • { if(popqstack(s)==NIL) • exit(0); • if((x1=gettopqstack(s))==NIL) • exit(0);
x2= expression[++j]; • } • else if(proceed(x1,x2)==‘=‘&& x1=‘#‘ && x2=‘#’) • { return 1; • } • else if(proceed(x1,x2)==‘ ‘) • break; • }
Printf(“\n错误!”); • return 0; • } • proceed(x1,x2)完成算符比较功能 • char proceed(char x1,char x2) • { • char result; • char midstring[2]; • result=‘<‘;
Midstring[0]=x2; • midstring[1]=‘\0’; • if(((x1==‘+’||x1==‘-’)&&strstr(“+-)#”,midstring)!=NULL || ((x1==‘*’||x1=‘/’)&&strstr(“+-*/)#”,midstring)!=NULL) ||(x1==‘)’)&&strstr(“+-*/)#”,midstring)!=NULL)) • { • result=‘>’; • }
Else if((x1==‘(‘&&x2==‘)’)|| • (x1==‘#’&& x2=‘#’)) • { • result=‘=‘; • } • Else if((x1==‘(‘&& x2==‘#’)|| • (x1==‘)’&& x2=‘(’)|| • (x1==‘#’&&x2==‘)’)) • { result=‘ ‘; • }
Return result; • } • 主函数如下: • #include <stdio.h> • #include <string.h> • #include<stdlib.h> • #define MAXNUM 100 • #define NIL 0 • typedef char elemtype;
Typedef struct • { • elemtype stack[MAXNUM]; • int top; • }qstype; • void initiateqstack(qstype *s); • int pushqstack(qstype*s,elemtype x); • elemtype popqstack(qstype *s);
elemtype gettopqstack(qstype *s); • char proceed(char x1,char x2); • Int postfix(qstype *s,char *expression); • main() • { • char expression[80]={“A+(B-C/D)*E”}; • qstype s; • printf(“\n”);