Wednesday 22 August 2012

Program for conversion from infix to postfix using push() and pop()

/* How to write Data structure Program for conversion from infix to postfix expression source code */

#include<stdio.h>
#include<conio.h>
#define max 50

typedef struct stack
{
int top;
char item[max];
}stack;
stack s1;

int push(char n)
{
if(s1.top==max-1)
puts("\nstack is full");
else
s1.item[++s1.top]=n;
return 0;
}

int pop()
{
if(s1.top==-1)
{
puts("\nstack is empty");
return 0;
}
else
return(s1.item[s1.top--]);
}

void main()
{
char inf[30],pos[30],ch,temp;
int i,j=0,valid=1;
s1.top=-1;
clrscr();
printf("\nenter infix expression:- ");
scanf("%s",&inf);
for(i=0;inf[i]!='\0';i++)
{
if(inf[i]=='(' || inf[i]=='{' || inf[i]=='[')
push(inf[i]);
if(inf[i]==')' || inf[i]=='}' || inf[i]==']')
if(s1.top==-1)
valid=0;
else
{
temp=pop();
if( inf[i]==')' && (temp=='{' || temp=='[') )
valid=0;
if( inf[i]=='}' && (temp=='(' || temp=='[') )
valid=0;
if( inf[i]==']' && (temp=='(' || temp=='{') )
valid=0;
}
}
if(s1.top>=0)
valid=0;
if( valid==1 )
{
for(i=0;inf[i]!='\0';i++)
{
if((inf[i]>=65 && inf[i]<91)||(inf[i]>=97 && inf[i]<123))
pos[j++]=inf[i];
if(inf[i]=='('||inf[i]=='{'||inf[i]=='['||inf[i]=='+'||inf[i]=='-'||inf[i]=='*'||inf[i]=='/'||inf[i]=='%')
push(inf[i]);
if(inf[i]==')'||inf[i]=='}'||inf[i]==']')
{
while(s1.top!=-1)
{
ch=pop();
if(ch!='('&&ch!='['&&ch!='{')
pos[j++]=ch;
}
}
}
pos[j]='\0';
printf("\npostfix expression is:- %s",pos);
}
else
printf("\nNot Valid expression\n");
getch();
}
Share This
Previous Post
Next Post

FYJC XI standard online admisson Process and declaraton of Merit list . Cut off List For prevous year also . 10 Th Results onlne declaraton Maharashtra Region .

0 comments: