Wednesday, August 28, 2013

Program to Convert Infix expression to prefix Expression

/*Program to Convert Infix expression to prefix Expression*/

#include <stdio.h>
#include <string.h>
#include<malloc.h>

#define MAX 50

struct infix
{
char target[MAX];
char stack[MAX];
char *s,*t;
int top,l;
};



void initinfix ( struct infix *p )
{
p -> top = -1 ;
strcpy ( p -> target, "" ) ;
strcpy ( p -> stack, "" ) ;
p -> l = 0 ;
}

void strrev(char *x)
 {
int i,j=0;
char *t;
t=(char *)malloc(sizeof(char)*strlen(x));
for(i=strlen(x)-1;i>=0;i--)
{
t[j++]=x[i];
}
x=t;
//return x;
 }
void setexpr ( struct infix *p, char *str )
{
p->s=str;
strrev(p->s);
p->l=strlen(p->s);
*(p->target+p->l)='\0';
p->t=p->target + (p->l-1);
}


void push ( struct infix *p, char c )
{
if (p->top==MAX-1)
printf ("Stack is full.\n");
else
{
p->top++;
p->stack[p->top]=c;
}
}


char pop (struct infix *p)
{
if (p->top==-1)
{
printf("Stack is empty.\n");
return -1;
}
else
{
char item = p->stack[p->top];
p->top--;
return item ;
}
}

int priority (char c)
{

if(c=='*'||c=='/'||c=='%')
return 2 ;
else
{
if(c=='+'||c=='-')
return 1 ;

else return 0 ;
}
}

void convert (struct infix *p)
{
char opr;

while (*(p->s))
{
if(*(p->s) == ' ' || *(p->s) == '\t')
{
p->s++;
continue ;
}

if (isdigit(*(p->s))||isalpha(*(p->s)))
{
while(isdigit(*(p->s)) || isalpha(*(p->s)))
{
*(p->t) = *(p->s);
p->s++;
p->t--;
}
}

if(*(p->s)==')')
{
push(p,*(p->s));
p->s++;
}

if (*(p->s) == '*' || *(p->s) == '+'||  *(p->s) == '/' || *(p->s ) == '%'|| *(p->s) == '-'|| *(p->s) == '$' )
{
if (p->top!=-1)
{
opr=pop(p);

while (priority(opr)>priority(*(p->s)))
{
*(p->t) = opr;
p->t--;
opr = pop(p);
}
push (p,opr);
push (p,*(p->s));
}
else
push (p,*(p->s));
p->s++;
}

if(*(p->s) == '(')
{
opr=pop(p);
while (opr!=')')
{
*(p->t)=opr;
p->t--;
opr=pop(p) ;
}
p->s++;
}
}

while (p->top!=-1)
{
opr=pop(p);
*(p->t)=opr;
p->t--;
}
p->t++;
}




void show (struct infix p)
{
while(*(p.t))
{
printf(" %c",*(p.t));
p.t++;
}
}






int main()
{
struct infix q ;
char expr[MAX] ;

initinfix(&q);

printf("Enter infix expression : " ) ;
gets(expr);

setexpr(&q,expr);
convert(&q);

printf ("\nThe Prefix expression is: ");
show(q);
printf("\n");

return 0;
}




No comments: