Remove a loop · Compiler

Remove a loop

Walk from the head. If a next link would take you back to a node already visited, clear that link so the current node becomes the tail. Keep track of which node you changed, then traverse the repaired list.

Input
Read n (1 <= n <= 100), then n rows of value next. Row i describes node ID i, numbered from 1. The head is node 1. Each value is an integer in [-1000, 1000]. Each next is a node ID or 0 for the end. Every node is reachable from the head.
Output
On the first line print the ID of the node whose next link was cleared, or 0 if the list already ended. On the second line print the values from head to tail, separated by spaces.

Compiler Explorer runs your code when you run or check it.

Loading your exercise draft…