To Convert infix expression into postfix expression.

#include<stdio.h>

#include<ctype.h>

char s[20];

int top=-1;

int priority(char c);

int main()

 {

    int i,j;

    char infix[30],postfix[30];

    printf("\n Enter Infix Expression:");

    gets(infix);

    for(i=0,j=0;infix[i]!='\0';i++)

     {

       if(infix[i]=='(')

{

  top=top+1;

  s[top]=infix[i];

}

       else if(isalpha(infix[i])||isdigit(infix[i]))

{

  postfix[j]=infix[i];

  j=j+1;

}

       else if(infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/'||infix[i]=='%'||infix[i]=='^')

       {

if(top==-1)

   {

     top=top+1;

     s[top]=infix[i];

   }

else

   {

      if(priority(infix[i])>priority(s[top]))

{

  top=top+1;

  s[top]=infix[i];

}

      else if(priority(infix[i])<=priority(s[top]))

       {

while(priority(infix[i])<=priority(s[top]))

    {

       postfix[j]=s[top];

       top=top-1;

       j=j+1;

    }

top=top+1;

s[top]=infix[i];

       }

   }

       }

     else if(infix[i]==')')

      {

while(s[top]!='(')

  {

    postfix[j]=s[top];

    top=top-1;

    j=j+1;

  }

top=top-1;

      }

     else

printf("\n Invalid Infix Expression");

  }

  while(top!=-1)

    {

      postfix[j]=s[top];

      top=top-1;

      j=j+1;

    }

  postfix[j]='\0';

  printf("\n Postfix Expression is");

  puts(postfix);

  return 0;

}

  int priority(char c)

   {

     switch(c)

       {

  case'(':return 0;

  case'+':

  case'-':return 1;

  case'*':

  case'/':

  case'%':return 2;

  case'^':return 3;

       }

     return 0;

   }



Comments

Popular posts from this blog

Create a Binary Search Tree of integers and perform the following operations (i)insert (ii) delete (iii). Search (iv) traversals (pre-order, in-order, post-order) BST

Creation Of DLL

Develop non-recursive functions to perform search for a Key value in a given list using (i) Binary Search Non Recursive