Sunday, 25 September 2011

Infix to Postfix

Write a C pogram to convert an infix expression to postfix expression using the concept of stacks.


#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>

#define SIZE 20

int pos;

struct stack
{
  int top;
  char items[SIZE];
};

void push(struct stack *s,char ch)
{
  if(s->top==(SIZE-1))
  return;
  s->items[++s->top]=ch;
}

char pop(struct stack *s)
{
  char y;
  if(s->top==-1)
  printf("Stack is empty\n");
  else
  {
     y=s->items[s->top];
     s->top--;
     return y;
    }
}

int prec(char stopn, char inopn)
{
  int ip=0, sp=0;
  switch(stopn)
  {
    case '+' :
    case '-'  :   sp=2 ; break;
    case '*' :
    case '/'  :   sp=4; break;
    case '$' :   sp=5; break;
    case '(' :    sp= -1; break;
  }

 switch (inopn)
 {
   case '+' :
   case '-' : ip=1;break;
   case '*' :
   case '/' : ip =3;break;
   case '$' : ip=6;break;
   case '(' : ip=9;break;
  case ')' : ip=0;break;
  default : ip=8; break;
 }

if(sp>ip) return 1;
else return 0;
} //end of int prec()

int empty(struct stack *s)
{
   if(s->top== -1)return 1;
   else return 0;
}

char stacktop(struct stack *s)
{
   if(empty(s))
   {
      printf("underflow in stack\n");
      return;
    }
   else
   return (s->items[s->top]);
}

void main()
{
  struct stack s;
  char infix[50], postfix[50],symb;
  int i,rank=0;
  s.top= -1;
  printf("Enter infix string\n");
  scanf("%s",infix);
  if(infix[strlen(infix)-1] == '*' || infix[strlen(infix)-1] == '+' || infix[strlen  (infix)-1]== '-' || infix[strlen(infix)-1] == '/')
  {
    printf("Invalid expression\n");
    return;
   }
  for(i=0,pos=0; ((symb=infix[i])!= '\0'); i++)
  {
     if(isalpha(symb))
     {
        postfix[pos++] = symb;
        rank++;
      }
     else
     {
        while(! empty(&s) && prec(stacktop(&s),symb))
        {
           postfix[pos++] = pop(&s);
           rank--;
           if(rank<1)
          {
           printf("Invalid expression\n");
           return ;
           }
        }//end of while
      if(symb != ')' || empty(&s))
      push(&s,symb);
      else
      pop(&s);
     }//end of else
   }//end of for loop
 
   while(!empty(&s))
    {
       postfix[pos++] = pop(&s);
       rank--;
       if(rank<1)
       printf("Invalid expression\n");
    }

    if(rank== 1)
    {
       postfix[pos] = '\0';
       printf("%s",postfix);
    }
     else
         printf("Invalid expression\n");
   
}//end of main

No comments:

Post a Comment