eolymp
bolt
Try our new interface for solving problems
Problems

LinkedList Cycle starting point

LinkedList Cycle starting point

Time limit 1 second
Memory limit 128 MiB

Given a linked list. Return pointer to the node where cycle starts. If there is no cycle, return null.

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 detectCycle that returns a pointer to the node where cycle starts. If there is no cycle, return null.

// Java
ListNode detectCycle(ListNode head)
// C, C++
ListNode* detectCycle(ListNode *head)

Example

prb9898.gif

Function detectCycle returns null because this linked list does not contain a cycle.

prb10042_1.gif

Function detectCycle returns pointer to the node with value 3 - the starting point of the cycle.

Author Mykhailo Medvediev