Check that prev is not null to avoid NPE.

In some cases prev is set to null which causes NPEs - added a check to verify that  prev is not null before using its value.