#include<stdio.h>
#include<ctype.h>
#include<string.h>
main()
{
char infix[20],postfix[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);
stack[++top]='#';
while((ch=infix[i++])!='\0')
{
if(isalnum(ch))
postfix[j++]=ch;
else
{
switch(ch)
{
case '(':stack[++top]=ch;
break;
case ')':while((c=stack[top--])!='(')
postfix[j++]=c;
break;
default:while(preced(ch)<=preced(c=stack[top]))
{
postfix[j++]=c;
top--;
}
stack[++top]=ch;
}
}
}
while(top>0)
postfix[j++]=stack[top--];
postfix[j]='\0';
printf("\nresultant postfix expression:-%s",postfix);
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