Detect a loop · Compiler

Detect a loop

Start a slow pointer and a fast pointer at the head. In each round, move slow one next link and fast two next links. If either pointer reaches the end during a move, stop. Otherwise compare their node IDs after both moves. Find the first round in which they occupy the same node.

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
Print the value stored at the first meeting node, or NONE if a pointer reaches the end.

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

Loading your exercise draft…