Infix to postfix algorithm that takes care of unary operators

后端 未结 3 1843
南笙
南笙 2021-01-05 13:49

The I/p to the algo will be an expression like this:

a+(-b)
a*-b+c

i.e any expression that a standard C compiler would support.

Now

3条回答
  •  醉梦人生
    2021-01-05 14:33

    In your input, when you have 2 consecutive operators, the second operator will be unary. If you have more consecutive operators, all but the first will be unary operators.

    Transform all your unary - operators to an operand -1 and an operator *, and remove all unary + operators.

    If the first element is an operator, it is an unary operator.

    Parenthesis are a special case, but you can do a first pass in which you ignore them. In the following example - is consecutive to *.

    4*(-(5))
    

    and your tokens would become:

    4
    *
    (
    -1
    *
    (
    5
    )
    )
    

提交回复
热议问题