C:中缀到后缀之间的转换(一元操作:减去)

时间:2017-05-23 21:16:51

标签: c postfix-notation unary-operator

我已经有了一个关于如何将中缀转换为后缀表达式的算法,但它只是有限的正数。我的问题是:

  1. 如果中缀表达式中有负数,怎么样?
  2. 是否有另一种将中缀转换为带有负数的后缀的算法?
  3. 如何评估后缀表达式?
  4. 我如何编辑我的代码以适应你的减号?
  5. 例如: 缀: -4 *(4 + 9 * 5 + - (9 + -4 / 2))= 后缀:?

    我使用的代码 - >

    void infixTopostfix(char infix[], char postfix[],int x)
    {
        int i,j=0;
        stack s;
        intialize(&s);
        for(i=0,j=0; i<x ; i++)
        {
            if(infix[i]>='0')
            {
                postfix[j]='(';
                j++;
                for(; (!value(infix[i]))&&(infix[i]!=')')&&(infix[i]!='\0'); i++)
                {
                    postfix[j]=infix[i];
                    j++;
                }
                postfix[j]=')';
                j++;
                i--;
            }
            else if(infix[i]=='(')
            {
                push(&s,infix[i]);
            }
            else if(infix[i]==')')
            {
                while(top(&s)!='(')
                {
                    postfix[j]=pop(&s);
                    j++;
                }
                pop(&s);
            }
            else if(infix[i]<'0')
            {
                while((value(infix[i])<=value(top(&s)))&&(!isempty(&s)))
                {
                    postfix[j]=pop(&s);
                    j++;
                }
                push(&s,infix[i]);
            }
        }
        while(!isempty(&s))
        {
            postfix[j]=pop(&s);
            j++;
        }
        postfix[j]=0;
    }
    
    float evaluate_postfix(char postfix[])
    {
        int i,j;
        float p,r;
        char number[10];
        stack s;
        intialize(&s);
        for(i=0; postfix[i]!='\0'; i++)
        {
            switch (postfix[i])
            {
            case '+':
                r=pop(&s);
                p=pop(&s);
                push(&s,r+p);
                break;
            case '/':
                r=pop(&s);
                p=pop(&s);
                push(&s,p/r);
                break;
            case '*':
                r=pop(&s);
                p=pop(&s);
                push(&s,r*p);
                break;
            case '-':
                r=pop(&s);
                p=pop(&s);
                push(&s,p-r);
                break;
            default:
                i++;
                for(j=0; (postfix[i]!=')')&&(postfix[i]!='\0'); i++)
                {
                    number[j]=postfix[i];
                    j++;
                }
                number[j]='\0';
                push(&s,atof(number));
            }
        }
        return pop(&s);
    }
    

0 个答案:

没有答案