Infix to Postfix Conversion in C
Infix to Postfix Conversion in C
#include stdio.h
#include ctype.h
#include string.h
char stack[100];
int top = -1;
void push(char x)
{
top++;
stack[top] = x;
}
char pop()
{
if(top==-1)
return -1;
else
return stack[top--];
}
int priority(char p)
{
if (p == '(')
return 0;
else if (p == '/' || p == '*')
return 2;
else if (p == '+' || p == '-')
return 1;
else
return 0;
}
void main()
{
int i=0;
char exp[100];
printf("\nEnter infix-equation\n");
scanf("%s", exp);
printf("\nPost-fix equation:\n");
while (exp[i] != '\0')
{
if (exp[i] == '(')
{
push(exp[i]);
}
else if (isalnum(exp[i]))
{
printf("%c", exp[i]);
}
else if (exp[i] == ')')
{
char d;
while (d=pop() != '(')
{
printf("%c", d);
}
}
else
{
while (priority(stack[top] >= priority(exp[i])))
{
printf("%c", pop());
}
push(exp[i]);
}
i++;
}
while (top != -1)
{
printf("%c", pop());
}
}
Output:
ReplyDeleteEnter infix-equation
a*d/c-e+f
Post-fix equation:
adcef+-/*