简体   繁体   中英

Precedence of operators in infix to postfix conversion

I'm creating a program in C that converts an expression in infix form to postfix form using the reverse polish algorithm through a stack implementation. However, I'm having trouble with how an incoming token having the same precedence as the topmost element of the stack should be placed. For example, given the infix form: (a+bc/d+e^f^2), the postfix form should be: ab+cd/-ef2^^+. However, my program outputs: ab+cd/-ef^2^+. I think the problem lies with this part of my code:

while(priority(token) <= priority(top_elem(&S)) && !isStackEmpty(&S)){
    x = POP(&S);
    printf("%c", x);
}
PUSH(&S, token);

By the way, this part only executes for operator tokens ('+', '-', ' ', '/', '^) and the open parenthesis. The priority function returns 0 for the open parenthesis, 1 for '+' and '-', 2 for ' ' and '/', and 3 for '^'.

I was wondering what I should change in my program. It executes fine for other inputs, though.

You have a problem of associativity: while (a * b) * c == a * (b * c) holds true, the same does not hold for powerTo (or ^ ): (a ^ b) ^ c != a ^ (b ^ c) .

You need to resolve this for each operand when their priorities match up:

while(!isStackEmpty(&S) &&
      (priority(token) < priority(top_elem(&S)) ||
       priority(token) == priority(top_elem(&S)) && !isRightAsoc(token)))
{
    x = POP(&S);
    printf("%c", x);
}
PUSH(&S, token);

The simplest solution is to give all operators two precedence values: a left precedence and a right precedence. You always compare the left precedence of the symbol on the stack with the right precedence of the input symbol.

One way to assign values is to make all left precedences even and all right precedences odd. The right precedence will be either one more or one less than the left precedence, depending on the operator's associativity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM