1 / 12

Infix to Postfix Expression Algorithm

Learn how to convert infix to postfix expressions using a stack-based algorithm in C language.

rferrell
Download Presentation

Infix to Postfix Expression Algorithm

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 中缀表达式变后缀表达式算法 • Int postfix(qstype *s,char *expression) • { • char x1,x2,x; • int j=0; • s-->stack[0]=‘#’; • s-->top=0; • x2=expression[j];

  2. If((x1=gettopqstack(s))==NIL) • exit(0); • while(1) • { • if(x2!=‘+’&& x2!=‘-’&& x2!=‘*’&& x2!=‘/’&& x2!=‘(‘ && x2!=‘)’ && x2!=‘#’) • { printf(“% c”,x2); • x2=expression[++j]; • }

  3. 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);

  4. 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);

  5. x2= expression[++j]; • } • else if(proceed(x1,x2)==‘=‘&& x1=‘#‘ && x2=‘#’) • { return 1; • } • else if(proceed(x1,x2)==‘ ‘) • break; • }

  6. Printf(“\n错误!”); • return 0; • } • proceed(x1,x2)完成算符比较功能 • char proceed(char x1,char x2) • { • char result; • char midstring[2]; • result=‘<‘;

  7. Midstring[0]=x2; • midstring[1]=‘\0’; • if(((x1==‘+’||x1==‘-’)&&strstr(“+-)#”,midstring)!=NULL || ((x1==‘*’||x1=‘/’)&&strstr(“+-*/)#”,midstring)!=NULL) ||(x1==‘)’)&&strstr(“+-*/)#”,midstring)!=NULL)) • { • result=‘>’; • }

  8. Else if((x1==‘(‘&&x2==‘)’)|| • (x1==‘#’&& x2=‘#’)) • { • result=‘=‘; • } • Else if((x1==‘(‘&& x2==‘#’)|| • (x1==‘)’&& x2=‘(’)|| • (x1==‘#’&&x2==‘)’)) • { result=‘ ‘; • }

  9. Return result; • } • 主函数如下: • #include <stdio.h> • #include <string.h> • #include<stdlib.h> • #define MAXNUM 100 • #define NIL 0 • typedef char elemtype;

  10. Typedef struct • { • elemtype stack[MAXNUM]; • int top; • }qstype; • void initiateqstack(qstype *s); • int pushqstack(qstype*s,elemtype x); • elemtype popqstack(qstype *s);

  11. 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”);

  12. Postfix(&s,strcat(expression,“#”)); • }

More Related