Search code examples
algorithmshunting-yard

Have to implement Shunting-yard algorithm, need help understanding it


I'm trying to implement an Shunting-yard algorithm with no parenthesis, but I'm having trouble understanding it. I have tried wikipedia but the entry is really bad. I should have little problem implementing the code, but if I don't get I can't implement it.

Now: how does this algorithm work ?

Here is what I do understand:

  • Go from left to right, all number are added to output queue, all operands are added to a stack. Once you reach the end you pop all operands and add them to the output

    Expression: 2+5*4+3/5   ( = 2+20+0.6 = 22.6 )
    
    Stack: +*+/             ( -> top )
    
    OutputQueue: 5 3 4 5 2  ( -> exits)
    

Now I pop the stack and add it to the queue

    OutputQueue: (insert ->) + * + / 5 3 4 5 2   ( -> exit)

So as far as I understand the form should be: 25435/+*+

Let's try and solve it:

    5/3 ~ 1.6 + 4 ~= 5.6 * 5 ~= 28 + 2 ~= 30 (or 30.3 recurring .3 if you insist)

EDIT: I am sure the Reverse Polish notation I used here is correct, so that should not be the issue.

I know I'm doing something stupid, but for the life of me I can't figure it out.

I think it would help most if someone could point out the error in my logic, because the algorithm should be good, since it's from wikipedia and I've seen others point me towards it. So it has to be good, I'm just messing up something somewhere.

Is it the queue ? I'm pretty sure I'm handling the Reverse Polish notation well enough.


Solution

  • You got it wrong :

    Expression: 2+5*4+3/5 
    

    For each token :

        token : 2
        outputqueue 2
        stack
    
        token : +
        outputqueue 2
        stack +
    
        token : 5
        outputqueue 25
        stack +
    
        token : "*" 
        "*" has higher predencence as "+", so we push into the stack
        outputqueue 25
        stack +*
    
        token : 4
        outputqueue 254
        stack +*
    
        token : "+"
        "+ "has lower predencence as "*", we pop "*" from the stack.
        "+" has same predecence as "+", so we pop "+" from the stack then add the current  token "+" in the stack
        outputqueue 254*+
        stack +
    
        token : 3
        outputqueue 254*+3
        stack +
    
        token : "/"
        "/" has lower predencence as "+", we push "/" into the stack
        outputqueue 254*+
        stack +/
    
        token : 5
        outputqueue 254*+35
        stack +/
    

    Expression is over, pop the stack :

    output 254*+35/+
    

    Calculation :

    5*4 = 20
    2+20 = 22
    3/5 = 0.6
    22 + 0.6 = 22.6