Reputation: 43
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+b-c/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.
Upvotes: 1
Views: 4594
Reputation: 241881
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.
Upvotes: 2
Reputation: 4283
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);
Upvotes: 2