Parse html on first and last occurrence of a matrix block type in a series of that same block type
You need to define the block previous/next variables outside of your for loop. Also you should check for the last element in the loop.

You can find a great working example on the happy lager demo website (https://github.com/pixelandtonic/HappyLager). 

The relevant code part is here: https://github.com/pixelandtonic/HappyLager/blob/master/craft/templates/_includes/article_body.html.