Sunteți pe pagina 1din 4

Infix <--> Postfix

#include<stdio.h>
#define SIZE 50 //Size of Stack
#include <ctype.h> //Type of header file in c that is use for mapping Character;
char st[SIZE];
int top=-1; //Global
push(char a)
{
st[++top]=a;
}
char pop()
{
return(st[top--]);
}
int pr(char a)
{
switch(a)
{
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}
int main()
{
char in[50],po[50],c,e;//c=char, e=element, in=infix, po=postfix
int i=0,k=0;
printf("\nPlease ENTER the infix Term = ");
scanf("%s",in);
push('#');
while((c=in[i])!='\0')//'\0'=NULL
{
if(c=='(')
push(c);
else
if(isalnum(c))
po[k++]=c;//Alphanumeric
else
if(c==')')
{
while(st[top]!='(')
po[k++]=pop();
e=pop();
}
else
{
while(pr(st[top])>=pr(c))
po[k++]=pop();
push(c);
}
i++;
}//End Of While Loop
while(st[top]!='#')
po[k++]=pop();
po[k]='\0';//'\0'=NULL
printf("\nEntered Value by the user is = %s",in);
printf("\n\nPostfix value is = %s",po);
return 0;
}

Infix <--> Prefix


#include<stdio.h>
#define SIZE 50 //Size of Stack
#include <ctype.h> //Type of header file in c that is use for mapping Character;
#include<string.h>
char st[SIZE];
int top=-1; //Global
push(char a)
{
st[++top]=a;
}
char pop()
{
return(st[top--]);
}
int pr(char a)
{
switch(a)
{
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}
int main()
{
char in[50],prf[50],c,e;//c=char, e=element, in=infix, prf=prefix
int i=0,k=0;
printf("\nPlease ENTER the infix Term = ");
scanf("%s",in);
push('#');
while((c=in[i])!='\0')//'\0'=NULL
{
if(c==')')
push(c);
else
if(isalnum(c))
prf[k++]=c;//Alphanumeric
else
if(c=='(')
{
while(st[top]!=')')
prf[k++]=pop();
e=pop();
}
else
{
while(pr(st[top])>=pr(c))
prf[k++]=pop();
push(c);
}
i++;
}//End Of While Loop
while(st[top]!='#')
prf[k++]=pop();
prf[k]='\0';//'\0'=NULL
strrev(prf);
strrev(in);
printf("\nEntered Value by the user is = %s",in);
printf("\n\nPrefix value is = %s",prf);
return 0;
}

S-ar putea să vă placă și