algorithm to fix a loopy list