Detect and remove loop in a linked list