infix to postfix best algorithm

Discussion in 'C' started by dass, Aug 31, 2007.

  1. dass

    dass New Member

    Joined:
    Aug 31, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Infix to postfix best algorithm

    Code:
    #include<stdio.h>
    #include<conio.h>
    
    int priority(char);
    
    void main()
    {
    	int i=0,j=0,len,sp=0,p1,p;
    	char infix[50],postfix[50],oprstack[45];
    	clrscr();
    	printf("enter the infix expression\n");
    	scanf("%s",infix);
    	len=strlen(infix);
    	oprstack[sp]='(';
    	infix[len]=')';
    	infix[len+1]='\0';
    	printf("%s",infix);
    
    	while(infix[i]!='\0')
    	{
    		if(isdigit(infix[i]) || isalpha(infix[i]))
    			postfix[j++]=infix[i];
    		else if(infix[i]=='(')
    		{
    			sp++;
    			oprstack[sp]=infix[i];
    		}
    		else if(infix[i]==')')
    		{
    			while(oprstack[sp]!='(')
    			{
    				postfix[j++]=oprstack[sp];
    				sp--;
    			}
    			sp--;
    		}
    		else
    			while(1)
    			{
    				p=priority(infix[i]);
    				p1=priority(oprstack[sp]);
    				if(p<=p1 && oprstack[sp]!='(')
    				{
    					postfix[j++]=oprstack[sp];
    					sp--;
    				}
    				else
    				{
    					sp++;
    					oprstack[sp]=infix[i];
    					break;
    				}
    			}
    			
    			i++;
    	}
    	postfix[j]=0;
    	printf("\nthe postfix expression is %s",postfix);
    	getch();
    }
    int priority(char ch)
    {
    	int k;
    	if(ch=='+' || ch=='-' )
    		k=1;
    	else if(ch=='*' || ch=='/' )
    		k=2;
    	else
    		k=0;
    	return k;
    }
    undefined
     
    Last edited by a moderator: Aug 31, 2007
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    What's your query?
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice