My Profile

I, Das ShrikKrishna J. MCA III IMSCD&R, Ahmednagar.

Monday, 15 August 2011

Infix To Postfix Conversion

# include<stdio.h>
# include<conio.h>
# include<string.h>
# include<stdlib.h>
# define MAX 30
int rear=-1,top=-1;
char stk[30],que[30],ch,chout;
int stkempty (int top)
{
if(top==-1)
{
return(1);
}
else
{
return(0);
}
}
int stkfull (int top)
{
if(top==MAX-1)
{
return(1);
}
else
{
return(0);
}
}
int push(char ch)
{
if(stkfull(top))
{
printf("\nstack is full cannot push into stack ");
return(top);
}
else
if(top==-1)
{
top++;
stk[top]='~';
}
top++;
stk[top]=ch;
return(top);
}
int pop()
{
if(stkempty(top))
{
printf("\nstack is empty cannot pop from stack ");
}
else
if(stk[top]!='~')
{
chout=stk[top];
top--;
}
return(chout);
}
int qempty (int rear)
{
if(rear==-1)
{
return(1);
}
else
{
return(0);
}
}
int qfull (int rear)
{
if(rear==MAX-1)
{
return(1);
}
else
{
return(0);
}
}
int addq(char ch)
{
if(qfull(rear))
{
printf("\nqueue is full cannot add in queue ");
return(rear);
}
else
{
rear++;
que[rear]=ch;
}
return(rear);
}
int isp(char ch)
{
switch(ch)
{
case '+' :
case '-' : return(1);
case '*' :
case '/' : return(2);
case '^' : return(3);
case '(' : return(0);
case '~' : return(-99);
}
return 0;
}
int icp(char ch)
{
switch(ch)
{
case '+' :
case '-' : return(1);
case '*' :
case '/' : return(2);
case '^' : return(4);
case '(' : return(4);
}
return 0;
}
 
int display(int len)
{
int i;
printf("\n Postfix conversion is \n");
for(i=0;i<=len;i++)
{
if(que[i]!='('&&que[i]!=')')
printf(" %c",que[i]);
}
return;
}
 
void postfix()
{
char str[10],ch;
int i,len;
printf("\nEnter the expression: ");
scanf("%s",str);
len=strlen(str);
printf("\n");
for(i=0;i<=len;i++)
{
ch=str[i];
if(ch>='a'&&ch<='z')
{
addq(ch);
}
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^'||ch=='('||ch==')')
{
if(ch==')')
{
while(chout!='(')
{
chout=pop();
addq(chout);
}
}
if(icp(ch)>isp(stk[top]))
{
push(ch);
}
else
{
chout=pop();
addq(chout);
push(ch);
}
}
}
while(stk[top]!='~')
{
chout=pop();
addq(chout);
}
display(len);
}
void main()
{
clrscr();
postfix();
getch();
}

No comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | cheap international calls