#include<stdio.h>
#include<ctype.h>
#include<string.h>
main()
{
char infix[20],prefix[20],stack[20],ch,c;
int top=-1,i=0,j=0;
int preced(char);
clrscr();
printf("enter a valid infix expression\n");
gets(infix);
strrev(infix);
stack[++top]='#';
while((ch=infix[i++])!='\0')
{
if(isalnum(ch))
prefix[j++]=ch;
else
{
switch(ch)
{
case ')':stack[++top]=ch;
break;
case '(':while((c=stack[top--])!=')')
prefix[j++]=c;
break;
default:while(preced(ch)<preced(c=stack[top]))
{
prefix[j++]=c;
top--;
}
stack[++top]=ch;
}
}
}
while(top>0)
prefix[j++]=stack[top--];
prefix[j]='\0';
strrev(prefix);
printf("\nresultant prefix expression:- %s",prefix);
getch();
}
int preced(char ch)
{
if(ch=='#'||ch==')')
return(0);
else if(ch=='+'||ch=='-')
return(1);
else if(ch=='*'||ch=='/'||ch=='%')
return(2);
else if(ch=='^'||ch=='$')
return(3);
}
No comments:
Post a Comment