GALLERY: N 2 Algorithm For Finding A Linked List Cycle
In a linked list , each element is a structure which contains the value of an element and the link to the next element. The next-link of the last element has a special value which marks the end (usually, null ). If a list has a cycle, the last element points to some element inside the list.
must eventually use the same value twice: there must be some pair of distinct indices i and j such that x i = x j . Once this happens, the sequence must continue periodically , by repeating the same sequence of values from x i to x j − 1 . Cycle detection is the problem of finding i and j , given f and x 0 .