eolymp
bolt
Try our new interface for solving problems
Problems

LinkedList Distance to Cycle

LinkedList Distance to Cycle

Given a linked list. Find the distance from the head of the list to the node where cycle starts. 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 DistanceToCycle that returns the distance from the head of the list to the node where cycle starts. If there is no cycle, return -1.

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

Example

prb9898.gif

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

prb10042_1.gif

Function DistanceToCycle returns 2 - the distance from the head of the list to the node where cycle starts. (123).

Time limit 1 second
Memory limit 128 MiB
Author Michael Medvediev