1. Middle of a Linked List
ListNode* middleOfLinkedList(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
2. Detect Cycle in a Linked List
bool hasCycle(ListNode *head)
{
if (!head || !head->next)
return false;
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
3. Return Node where Cycle begins
ListNode *findStartingPoint(ListNode *head)
{
if (!head || !head->next)
return NULL;
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return NULL;
}
4. Length of Loop
int findLength(ListNode *slow, ListNode *fast)
{
int len = 1;
slow = slow->next;
while (slow != fast)
{
len++;
slow = slow->next;
}
return len;
}
int findLengthOfLoop(ListNode *head)
{
if (!head || !head->next)
return 0;
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
return findLength(slow, fast);
}
}
return 0;
}