Infixtopostfix
Infixtopostfix
#include<stdio.h>
#include<string.h>
#define SIZE 10
char infix[SIZE],postfix[SIZE];
char stack[SIZE];
int top=-1;
void infixtopostfix();
void dsplay();
int precedence(char);
void push(char);
char pop();
int main()
{
printf("enter infix expression");
fgets(infix,SIZE,stdin);
infix[strcspn(infix, "\n")] = '\0';
infixtopostfix();
dsplay();
return 0;
}
void infixtopostfix()
{
int i,j=0;
char ch,x;
for(i=0;i<strlen(infix);i++)
{
ch=infix[i];
switch(ch)
{
case'(' : push(ch);
break;
case')' : while((x=pop())!='(')
{
postfix[j++]=x;
}
break;
case '*':
case '/':
case '+':
case '-':while(top!=-1&&precedence(stack[top])>=precedence(ch))
{
postfix[j++]=pop();
}
push(ch);
break;
default:postfix[j++]=ch;
break;
}
}
while(top!=-1)
{
postfix[j++]=pop();
}
postfix[j]='\0';
}
int precedence(char ch)
{
switch(ch)
{
case '^' :return 3;
break;
case '/' :
case '*' :return 2;
break;
case '+' :
case '-' :return 1;
break;
default :return 0;
break;
}
}
void push(char ch)
{
if(top==SIZE-1)
{
printf("stack is full");
}
else
{
top++;
stack[top]=ch;
}
}
char pop()
{
if(top==-1)
{
printf("stack is empty");
}
else
{
return stack[top--];
}
}
void dsplay()
{
printf("\n after conversion of infix to postfix is\n");
puts(postfix);
}