Infix to Postfix using stack

后端 未结 2 1234
走了就别回头了
走了就别回头了 2021-01-22 02:28

My lecturer gave me an assignment to create a program to convert an infix expression to postfix using Stack. I\'ve made the stack classes and some functions to read the infix ex

2条回答
  •  [愿得一人]
    2021-01-22 03:05

    [Program to convert infix to postfix using stack][1]
    
    C program to convert infix to postfix using stackC
    
    #define SIZE 50            
    #include 
    char s[SIZE];
    int top=-1;       /* Global declarations */
    
    push(char elem)
    {                       /* Function for PUSH operation */
        s[++top]=elem;
    }
    
    char pop()
    {                      /* Function for POP operation */
        return(s[top--]);
    }
    
    int pr(char elem)
    {                 /* Function for precedence */
        switch(elem)
        {
        case '#': return 0;
        case '(': return 1;
        case '+':
        case '-': return 2;
        case '*':
        case '/': return 3;
        }
    }
    
    main()
    {                         /* Main Program */
        char infix[50],postfix[50],ch,elem;
        int i=0,k=0;
        printf("\n\nEnter Infix Expression : ");
        scanf("%s",infix);
        push('#');
        while( (ch=infix[i++]) != '\0')
        {
            if( ch == '(') push(ch);
            else
                if(isalnum(ch)) postfix[k++]=ch;
                else
                    if( ch == ')')
                    {
                        while( s[top] != '(')
                            postfix[k++]=pop();
                        elem=pop(); /* Remove ( */
                    }
                    else
                    {       /* Operator */
                        while( pr(s[top]) >= pr(ch) )
                            postfix[k++]=pop();
                        push(ch);
                    }
        }
        while( s[top] != '#')     /* Pop from stack till empty */
            postfix[k++]=pop();
        postfix[k]='\0';          /* Make postfix as valid string */
        printf("\nPostfix Expression =  %s\n",postfix);
    }
    

提交回复
热议问题