eolymp
Competitions

Linked List practice

LinkedList Cycle length

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 (3453).

Time limit 1 second
Memory limit 128 MiB
Author Michael Medvediev