Given below is a program which converts an infix expression into its postfix form. #define MAX 1000 void main( ) { static char target[MAX], stack[MAX]; char*t, str[MAX], *s, n1, n2, item, nn; int p1, p2, i, top = -1 ; printf("\nEnter the infix expression:"); gets(str) ; s = str ; t = target ; while(*s) { if (*s == '`' || *s == '\t') { s++; continue; } if(isdigit (*s) || isalpha (*s)) { while (isdigit(*s) || isalpha (*s)) { *t = *s; t++; s++; } } if(*s == '(') { push (stack, &top, *s); s++; } if( *s == ')') { n1 = pop (stack, &top); while (n1)!='(' ) { *t = n1; t++; n1 = pop (stack, &top) ; } s++; } if(*s =='+' || *s =='*' || *s == '/' || *s == '%' ) { if ( top == -1) push(stack, &top, *s); else { n1 = pop (stack, &top); while( priority (n1) >= priority(*s ) ) { *t = n1; t++; n1 = pop (stack, &top) ; } push(stack, &top, n1); push(stack, &top, *s); } s++; } } while (top != -1) { n1 = pop (stack, &top); *t = n1; t++; } *t = '\0'; t=target; while(*t) { printf("%c", *t); t++; } } /*checks the priority of the operators*/ int priority(char ele) { int pri; char a, b, c; if ( ele =='*' || ele == '/'|| ele == '%' ) pri = 2; else { if(ele == '+' || ele == '-') pri = 1; else pri = 0; } return pri ; } void push(char *stk, int*sp, char item) { if (*sp == MAX) printf("\nStack is full"); else { *sp = *sp + 1; stk[*sp] = item; } } char pop (char *stk, int*sp) { int item; if(*sp == -1) { printf("\nStack is empty"); return(-1); } else { item = stk[*sp]; *sp=*sp - 1; return (item); } } |
|