c program :
#include <stdio.h>
#include <ctype.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char x)
{
if (top == MAX - 1)
printf("\nStack Overflow");
else
{
top = top + 1;
stack[top] = x;
}
}
char pop()
{
if (top == -1)
printf("\nStack Underflow");
else
return stack[top--];
}
int st_priority(char x)
{
if (x == '+' || x == '-')
return 1;
else if (x == '%' || x == '*' || x == '/')
return 2;
else if (x == '^')
return 3;
else
return 0;
}
int in_priority(char x)
{
if (x == '+' || x == '-')
return 1;
else if (x == '%' || x == '*' || x == '/')
return 2;
else if (x == '^')
return 4;
else
return 0;
}
char *infixtopostfix(char *infix, char *postfix)
{
char x, *e;
int j = 0, i = 0;
e = infix;
printf("\nCorresponding Postfix:");
while (*e != '\0')
{
if (isalnum(*e))
{
postfix[j] = *e;
j++;
i++;
}
// printf("%c",*e)
else if (*e == '(')
push(*e);
else if (*e == ')')
{
while ((x = pop()) != '(')
{
postfix[j] = x;
j++;
// printf("%c",x);
}
// x=pop();//remove left parenthesis
// i++;
}
else
{
while (top > -1 && st_priority(stack[top]) >= in_priority(*e))
{
postfix[j] = pop();
j++;
// printf("%c",pop());
}
push(*e);
i++;
}
e++;
}
while (top != -1 && stack[top] != '(')
{
postfix[j] = pop();
j++;
// printf("%c",pop());
}
postfix[j] = '\0';
return postfix;
}
int main()
{
char infix[50], postfix[50], *t;
printf("\nEnter an Infix Expression:");
scanf("%[^\n]s", infix);
t = infixtopostfix(infix, postfix);
printf("postfix: %s\n", t);
return 0;
}
Comments