Linked lists · Exercise 18 of 100

Remove a loop

Once you know the first node of the loop, start there and follow links until the next link would return you to that node. Clear that link to give the list a tail while keeping every node reachable from the head.

Try it yourself

From the head, the list visits 3, 6, 9, 12, 15, then returns to 9. Which node's next link should you clear so that a walk from 3 visits all five nodes exactly once and ends?

One-step hint

Trace from the head until an arrow would take you to an already visited node. Look at the node that arrow leaves.

Worked solution
  1. The first repeated node is 9. Starting there and following the loop takes you through 12 to 15.
  2. The link from 15 returns to 9. Clearing it leaves 15 as the tail after all five nodes have been visited.
DSA compiler