Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<ctype.h>
- #define MAX 100
- char infix[200], postfix[200], STACK[MAX];
- int top=-1;
- int isEmpty()
- {
- if(top==-1)
- return 1;
- else
- return 0;
- }
- int isFull()
- {
- if(top==MAX-1)
- return 1;
- else
- return 0;
- }
- void PUSH(char ch)
- {
- if(isFull())
- {
- printf("\nStack Overflow");
- exit(0);
- }
- else
- STACK[++top]=ch;
- }
- char POP()
- {
- if(isEmpty())
- {
- printf("\nStack Underflow");
- exit(0);
- }
- else
- {
- char ch=STACK[top--];
- return (ch);
- }
- }
- int precedence(char ch)
- {
- if(ch=='(' || ch==')')
- return 0;
- if(ch=='^')
- return 3;
- else if (ch=='*' || ch=='/' || ch=='%')
- return 2;
- else if(ch=='+' || ch=='-')
- return 1;
- else
- {
- printf("\nUnknown operator entered\n");
- exit(0);
- }
- }
- void infix_to_postfix()
- {
- int i=0, j=0; char ch, tmp;
- for(;infix[i]!='\0';i++)
- {
- ch=infix[i];
- if(ch==' ')
- continue;
- if(isalnum(ch))
- postfix[j++]=ch;
- else
- {
- if(isEmpty())
- {
- precedence(ch);
- PUSH(ch);
- continue;
- }
- if(!isFull())
- {
- if(ch=='(')
- {
- PUSH(ch);
- continue;
- }
- else if(ch==')')
- {
- tmp=POP();
- while(tmp!='(')
- {
- postfix[j++]=tmp;
- tmp=POP();
- }
- continue;
- }
- int pch=precedence(ch), pst=precedence(STACK[top]);
- while(pch<=pst)
- {
- if(isEmpty())
- break;
- tmp=POP();
- if(tmp=='(')
- {}
- else
- postfix[j++]=tmp;
- if(top==-1)
- {
- pst=-1;
- continue;
- }
- pst=precedence(STACK[top]);
- }
- PUSH(ch);
- }
- else
- {
- printf("\nStack Overflow. Please reduce the equation length");
- exit(0);
- }
- }
- }
- while(!isEmpty())
- postfix[j++]=POP();
- }
- int main()
- {
- printf("\nEnter the Infix Expression: ");
- gets(infix);
- infix_to_postfix();
- printf("\nThe expression after converting to Postfix is: %s",postfix);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement