Infix to Postfix

#include<stdio.h>
#include<string.h>
#define max 20

char stack[max];
int top=-1;

void push(char x)
{
    top++;
    stack[top]=x;
}

char pop()
{
    char x;
    x=stack[top];
    top--;
    return x;
}

int pre(char a)
{
    switch(a)
    {
        case '(': return 0;
        case '+': case '-': return 1;
        case '*': case '/': case '%': return 2;
        default: return 3;
    }
}

void main()
{
    char infix[50],postfix[50],ch,x;
    int i=0,p=0;
    printf("Enter infix expression ");
    scanf("%s",infix);
    while((ch=infix[i++])!='\0')
    {

        if(isalnum(ch))
            postfix[p++]=ch;
        else if(ch=='(')
            push(ch);
        else if(ch==')')
        {
            while(stack[top]!='(')
                postfix[p++]=pop();
            pop();
        }
        else
        {
            while(pre(ch)<=pre(stack[top])&&top!=-1)
            {
                postfix[p++]=pop();
            }
            push(ch);
        }
    }
    while(top!=-1)
    {
        postfix[p++]=pop();
    }
    postfix[p]='\0';
    printf("Postfix expression is %s",postfix);
}

/* Output:
Enter infix expression a*(c+d/e)-b
Postfix expression is acde/+*b-
*/

Leave a comment