Saturday, 27 September 2014

Infix to Postfix Conversion

$$$         Infix to Postfix Conversion           $$$

PROGRAM:

#include<iostream>
#include<string.h>
#include<ctype.h>
#define SIZE 50
char s[SIZE],infix[50],postfix[50],ch,item;
int i=0,k=0,len,top=-1;
class itop
{
      public:
      int convert()
      {
            push('#');
            len=strlen(infix);
            for(i=0;i<len;i++)
            {
                  ch=infix[i];
                  if(isalnum(ch))
                  {
                        postfix[k]=ch;
                        k++;
                  }
                  else if(ch=='(')
                  {
                        push(ch);
                  }
                  else if(ch==')')
                  {
                        while(s[top]!='(')
                        {
                              postfix[k]=pop();
                              k++;
                        }
                        item=pop();
                  }
                  else
                  {
                        while(priority(s[top])>=priority(ch))
                        {
                              postfix[k]=pop();
                              k++;
                        }
                        push(ch);
                  }
            }
            while(s[top]!='#')
            {
                  postfix[k]=pop();
                  k++;
            }
            postfix[k]='\0';
      }

      void push(char a)
      {
            top=top+1;
            s[top]=a;
      }
      char pop()
      {
            char a;
            a=s[top];
            top=top-1;
            return a;
      }
      int priority(char a)
      {
            switch(a)
            {
                  case '#':return 0;
                  case '(':return 1;
                  case '+':return 2;
                  case '-':return 2;
                  case '*':return 3;
                  case '/':return 3;
                  case '^':return 4;
            }
      }
};

void main()
{
      itop ip;
      cout<<"\n\n $$$ INFIX TO POSTFIX CONVERSION $$$ \n\n";
      cout<<"Enter infix expression:\t";
      cin>>infix;
      ip.convert();
      cout<<"Postfix expression is:"<<postfix;
}


OUTPUT:

$$$ INFIX TO POSTFIX CONVERSION $$$

Enter infix expression: (A+B^C)*D+E^5


Postfix expression is: ABC^+D*E5^+

No comments:

Post a Comment