0

我想将中缀转换为后缀表达式。

oki 我得到了它的工作,但我很难弄清楚如果你输入像 5 * 3 + -1.2 那么如果你想要负数,它就行不通了。这是我的代码:

void infix2postfix(char* infix, char* postfix){
     char *in,*post;
        Stack<char>Q;
        char n;
        in = &infix[0];
        post = &postfix[0];
        while(*in){
            while(*in == ' ' || *in == '\t'){
                in++;
            }
            if( isdigit(*in) || isalpha(*in) ){
                while( isdigit(*in) || isalpha(*in)){
                    *post = *in;
                    post++;
                    in++;
                }
            }
            if( *in == '(' ){
                Q.Push(*in);
                in++;
            }
            if( *in == ')'){
                n = Q.Pop();
                while( n != '(' ){
                    *post = n;
                    post++;
                    n = Q.Pop();
                }
                in++;
            }
            if( operand(*in) ){
                if(Q.IsEmpty())
                    Q.Push(*in);
                else{
                    n = Q.Pop();
                    while(priority(n) >= priority(*in)){
                        *post = n;
                        post++;
                        n = Q.Pop();
                    }
                    Q.Push(n);
                    Q.Push(*in);
                }
                in++;
            }
        }
        while(!Q.IsEmpty())
        {
            n = Q.Pop();
            *post = n;
            post++;

        }
        *post = '\0';
    }

它有效,但我希望它与一元运算符一起使用,因此它会接受输入4 * 5 + 4 + -1.2,因此每个数字之间都有一个空格,除非它是负数 -1.2。我的代码也不适用于大于 9 的整数,如果我输入 10,那么它只会乘以 1*0。.

4

1 回答 1

0

如果遇到 a -,则必须检测它是运算符(减法)还是否定。

我建议你检查以前的符号。如果前一个符号是运算符,那么“-”可能是否定的。

于 2012-12-10T20:42:46.017 回答