e-olymp
favorite We need a little bit of your help to keep things running, click on this banner to learn more
Competitions

class LinkedList

LinkedList Cycle starting point

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) {}
};

Implement function detectCycle that returns pointer to the node where cycle starts. If there is no cycle, return null.

// Java
ListNode detectCycle(ListNode head)
// 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.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev