You are on page 1of 2

/*infix to postfix conversion*/ #include<stdio.h> #include<stdlib.

h> struct stack { int top,size; char *p; }; struct stack *create(int max) { struct stack *s; s=(struct stack *)malloc(sizeof(struct stack)); s->top=-1; s->size=max; s->p=(char *)malloc(sizeof(char)*max); return s; } int isfull(struct stack *s) { if(s->top==s->size-1) return 1; return 0; } int isempty(struct stack *s) { if(s->top==-1) return 1; return 0; } void push(struct stack *s,char x) { if(!isfull(s)) s->p[++s->top]=x; } char pop(struct stack *s) { if(!isempty(s)) return s->p[s->top--]; } char peak(struct stack *s) { if(!isempty(s)) return s->p[s->top]; } int precedence(char ch) { switch(ch) { case '$': case '^':return 3;break; case '/': case '*':return 2;break; case '+': case '-':return 1;break; default :return 0; } } main() { char infix[20],postfix[20],c;

int i=0,j=0,n; struct stack *s; printf("enter the size of stack"); scanf("%d",&n); s=create(n); printf("enter the infix expression"); scanf("%s",infix); while(infix[i]!='\0') { if(isalpha(infix[i])) postfix[j++]=infix[i]; else if(infix[i]=='(') push(s,infix[i]); else if(infix[i]==')') { while(1) { c=pop(s); if(c=='(') break; postfix[j++]=c; } } else { while(!isempty(s)&&precedence(peak(s))>precedence(infix[i])) postfix[j++]=pop(s); push(s,infix[i]); } i++; } while(!isempty(s)) postfix[j++]=pop(s); postfix[j]='\0'; printf("postfix expression is %s",postfix); }

You might also like