Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<string.h>
- #include<ctype.h>
- #define MAX 100
- typedef struct
- {
- char s[MAX]; // Operator Stack
- char a[MAX]; //Infix Expression
- char b[MAX]; //Postfix Expression
- int tos; //Top of stack
- int postindex; //Index of Postfix. Don't ask why defined here. Just feeling like it :P
- }infix;
- void transfer(infix *t,char k)
- {
- t->b[t->postindex]=k;
- t->postindex++;
- }
- int ipr(char a)
- {
- if (a=='(')
- return 3;
- else if (a=='+'||a=='-')
- return 1;
- else if (a=='%'||a=='/'||a=='*')
- return 2;
- }
- int rpr(char a)
- {
- if (a=='(')
- return 0;
- else if (a=='+'||a=='-')
- return 1;
- else if (a=='%'||a=='/'||a=='*')
- return 2;
- }
- int isempty(infix *t)
- {
- if (t->tos==-1)
- return 1;
- else
- return 0;
- }
- void display(infix *t)
- {
- int i;
- int n=(int)strlen(t->b);
- for(i=0;i<n;i++)
- {
- printf("%s",t->b[i]);
- }
- }
- void push(infix *t,char a)
- {
- t->tos++;
- t->s[t->tos]=a;
- }
- void pop(infix *t,char k)
- {
- if(k=='(')
- {
- t->tos--;
- }
- else
- {
- transfer(t,k);
- t->tos--;
- }
- }
- int isoperand(char a)
- {
- if(a=='+'||a=='-'||a=='%'||a=='/'||a=='*'||a=='(')
- return 1;
- else
- return 0;
- }
- void convert(infix *t)
- {
- int i;
- int n=(int)strlen(t->a);
- for(i=0;i<n;i++)
- {
- if(isoperand(t->a[i]))
- {
- if (isempty(t))
- {
- push(t,t->a[i]);
- }
- else if(ipr(t->a[i])>rpr(t->s[t->tos]))
- {
- push(t,t->a[i]);
- }
- else if(ipr(t->a[i])<rpr(t->s[t->tos]))
- {
- while(isempty(t)!=1||ipr(t->a[i])>rpr(t->s[t->tos]))
- {
- pop(t,t->a[i]);
- }
- push(t,t->a[i]);
- }
- else if(t->a[i]==')')
- {
- while(t->s[t->tos]!='(')
- {
- pop(t,t->a[i]);
- }
- }
- else
- {
- transfer(t,t->a[i]);
- }
- }
- }
- }
- void main()
- {
- infix s;
- s.postindex=0;
- s.tos=-1;
- printf("Enter the infix expression\n");
- gets(s.a);
- convert(&s);
- printf("\nThe Postfix expression is \n");
- display(&s);
- getchar();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement