Find the starting point of the loop

June 23, 2022 · 1 min read

https://leetcode.com/problems/linked-list-cycle-ii/

class Solution {
public:
  ListNode *detectCycle(ListNode *head) {
    if (head == NULL || head->next == NULL)
      return NULL;

    ListNode *slow = head;
    ListNode *fast = head;
    bool isCycle = false;

    while (slow != NULL && fast != NULL) {
      slow = slow->next;
      if (fast->next == NULL)
        return NULL;
      fast = fast->next->next;
      if (slow == fast) {
        isCycle = true;
        break;
      }
    }

    if (!isCycle)
      return NULL;
    slow = head;
    while (slow != fast) {
      slow = slow->next;
      fast = fast->next;
    }

    return slow;
  }
};
Delete loop in a linked list
Remove duplicates in a sorted linked list