let's see if I can break it down for you. Shunting yard algorithm does one of the following by breaking a infix notation:
- either produce a postfix notation string(also known as Reverse Polish notation)
- or an abstract syntax tree.
In you case, it's postfix notation.
[note: I hope you know about postfix notation, if not then, read this.]
Now, postfix notation makes it very easy to evaluate a mathematical expression. I'll show you how to evaluate a postfix notation:
In a simple description:
(1) Infix: A + B
Postfix: A B +
(2) Infix: A + B * C
Postfix: A B C * +
Let's observe the part A+B*C i.e. A+(B*C)
If we represent it in Postfix, it would be like: A B C * +(by applying shunting-yard)
Now, the algorithm to calculate it
(1) Take a stack
(2) When we see a number, we push it to stack
(3) When we see a operator, we pop two numbers out of stack and calculate them with help of operator and push the result into stack again
(4) We do it till the end
(5) At last, only a number would be left in stack, that is our answer.
Let's visualise it:
(1) [A]
(2) [A, B]
(3) [A, B, C]
(4) [A, R1] where R1 = B*C
(5) [R2] where R2 = A+R1
I hope, you have understood that, shunting yard will help you convert infix to postfix and then, you can easily evaluate the postfix notation.
Now, the question is how to detect a++b
error:
Now, observe what happens for a, +, +, b tokens(as you've stated in the comment: a++b
is tokenized a, +, +, b tokens):
I've taken the pseudocode from wikipedia(got lazy, didn't want to write myself):
else if the token is an operator then:
while ((there is a operator at the top of the operator stack)
and ((the operator at the top of the operator stack has greater precedence)
or (the operator at the top of the operator stack has equal precedence and the token 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.
push it onto the operator stack.
accroding to this: a, +, +, b would take the following form in output queue:
a, b, +, +
a, b, +, +
is just simply wrong, cause, according to the postfix evaluation rules the following would occur:
1. [a] // output queue is now [b, +, +]
2. [a, b] // output queue is now [+, +]
3. [r1] // output queue is now [+]
4. error // cause: notice there's still one '+' operator left in queue
// but, only one number 'r1' left in the 'stack'
// so, error
I hope it is clear to you now...