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
  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)



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


Function CycleLength returns 3 - the length of the cycle (3453).

Time limit 1 second
Memory limit 128 MiB
Author Michael Medvediev