Reputation: 25
So this expression, A - B + C * (D / E) results to A B - C D E / * +
I thought when converting infix to postfix, you have to keep the operators in stack until you see operators with lower precedence after it or at the end of the expression and you just write it all down.
But minus sign has the same level of precedence as the plus, so why minus sign is written down and not keeping it to stack?
I think there's something wronf with my understanding with the method of converting. Please provide an explanation, preferably with a step by step solution. I am really confused what happens to the minus sign as I understand the conversion differently. Thank you so much.
Upvotes: 0
Views: 26
Reputation: 133985
The Shunting yard algorithm rules state:
if the token is an operator, then:
while ((there is a function at the top of the operator stack)
or (there is an operator at the top of the operator stack with greater precedence)
or (the operator at the top of the operator stack has equal precedence and is left associative))
and (the operator at the top of the operator stack is not a left parenthesis):
pop operators from the operator stack onto the output queue.
Note the second or
condition: the operator at the top of the operator stack has equal precedence and is left associative.
The +
and -
operators have equal precedence, and are left-associative. Therefore, you would remove the -
operator when you see the +
.
See also https://www.geeksforgeeks.org/operator-precedence-and-associativity-in-c/. Although that's specific to C, most languages use the same precedence and associativity for common operators.
Upvotes: 1