C Program to convert a Infix Expression to Postfix Expression...

#include<stdio.h>
#include<string.h>
#define maxi 100

struct stack       // Structure of a stack...Note Here Character array is used..
{
char ar[maxi];
int t;
};

void push(struct stack *p,char c)      // To insert an element to an stack..
{
 if(p->t==maxi-1){
  printf("\nStack Overflow.");
  return;
 }
 p->ar[++p->t]=c;
}

char pop(struct stack *p)               // To return and delete the last element in the stack..
{
 if(p->t!=-1){
 return p->ar[p->t--];
}
}

char peep(struct stack p)           // To return the last element in the stack..
{
 return p.ar[p.t];
}

int isoperator(char c)               // Function to check whether the character is opearator or not...
{
 if(c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='('||c==')')
   return 1;
 else
   return 0;
}

int priority(char c)             // Function to return the priority of the given operator(character)
{
 if(c=='+'||c=='-')
  return 1;
else if(c=='*'||c=='/'||c=='%')
  return 2;
 else
  return 0;
}

void main()
{
 struct stack s;
 s.t=-1;
 char a[100],b[100];
 int x,y,z;
 x=1;
 y=2;
 int i,c=0,j=0;
 printf("Enter the Infix Expression..");
 scanf("%s",b);                         // Infix expression is inputed as a string in variable b...
 for(i=0;i<strlen(b);i++){
   if(!isoperator(b[i])){            // If character is not an operator directly copy it to the output string a... 
      a[j++]=b[i];
      continue;
    }
   else{                                    // If character is an operator,proceed further here...
    if(priority(b[i])==0){         // Corner Case to handle Parentheses...
     if(c==1){                          // Corner Case to handle Close Parentheses...
       while(priority(peep(s))!=0){
           a[j++]=pop(&s);        // Pop all the elements in the stack till starting curly brace...
       }
       char t=pop(&s);             // Pop the starting curly brace also...
       c--;
     }
     else{                               // If the curly brace is a starting one..Just push it to stack...
     push(&s,b[i]);
     c++;
    }
    goto endline;                  // To skip and go to the next iteration...
  }
  }
 if(priority(peep(s))<priority(b[i]))      // Case to handle other operators..
   push(&s,b[i]);
 else{                                                   // Pop till you meet an operator with strictly lower precedence
 a[j++]=pop(&s);                                     than the current one...
 push(&s,b[i]);
 }
 endline:
 z=x+y;
 }
 while(s.t!=-1){                // Pop the remainings of the stack to the output string a...
  a[j++]=pop(&s);
 }
 a[j]='\0';
    printf("\nThe postfix Expression is..%s",a);    //Postfix Expression is displayed as a string in a...
}

No comments:

Post a comment