Problems
LinkedList Cycle starting point
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) {}
};
// 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
Function detectCycle returns null because this linked list does not contain a cycle.
Function detectCycle returns pointer to the node with value 3 - the starting point of the cycle.