LinkedList Cycle length#10763

LinkedList Cycle length

1 second
128 megabytes
Easy

Given a linked list. Find the length of its cycle. If there is no cycle, return -1.

Definition of a single linked list:

// Java
class ListNode {
  int val;
  ListNode next;
  ListNode(int x) {
    val = x;
    next = null;
  }
}
// C++
class ListNode
{
public:
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};
// C
struct ListNode
{
  int val;
  struct ListNode *next;
};

Implement a function CycleLength that returns a length of a cycle. If there is no cycle, return -1.

// Java
int CycleLength(ListNode head)
// C, C++
int CycleLength(ListNode *head)

Example

prb9898.gif

Function CycleLength returns -1 because this linked list does not contain a cycle.

prb10042_1.gif

Function CycleLength returns 3 - the length of the cycle (3 → 4 → 5 → 3).