Wednesday 22 August 2012

Program for infix to prefix conversion | Data Structure | how to write code

/* Data structure program for infix to prefix conversion with output */

#include<stdio.h>
#include<conio.h>
#include<string.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],pre[30],temp,ch;
int i,j=0,l,valid=1;
s1.top=-1;
clrscr();
printf("\nenter infix expression:- ");
scanf("%s",&inf);
l=strlen(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=l;i>=0;i--)
{
if((inf[i]>=65 && inf[i]<91)||(inf[i]>=97 && inf[i]<123))
pre[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!=')')
pre[j++]=ch;
}
}
}
pre[j]='\0';
printf("\nprefix expression is:- %s",strrev(pre));
}
else
printf("\nNot Valid Expression");
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: