Detect a Linked-List Cycle
Problem statement
A singly linked list is serialized by an integer array next. Node i points to node next[i]; a value of -1 means null. When the array is non-empty, node 0 is the head. Entries that are not reachable from node 0 are ignored.
Return true if following next pointers from the head eventually revisits a node. Return false for an empty list or when traversal reaches null.
Function
hasLinkedListCycle(next: int[]) → booleanExamples
Example 1
next = [1,2,3,1]return = trueTraversal from node 0 enters the cycle 1 -> 2 -> 3 -> 1.
Example 2
next = [1,2,3,-1]return = falseTraversal reaches node 3 and then null.
Example 3
next = [0]return = trueThe head points to itself.
Example 4
next = []return = falseThe empty array represents an empty list.
Constraints
0 <= next.length <= 200000.- For every index
i,next[i] == -1or0 <= next[i] < next.length.