Linked List Cycle II in C++

Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node. The constraint is that we cannot modify the list

To solve this, we will follow these steps −

  • slow := head and fast := head

  • while slow, fast and next of fast is available, then

    • slow := next of slow

    • fast := next of (next of fast)

    • if slow = fast, then break

  • if fast is not empty or next of first is not empty, then return null

  • if slow = fast, then

    • slow := head

      • slow := next of slow and fast := next of fast

  • return slow


Let us see the following implementation to get better understanding −

class Solution {
   ListNode *detectCycle(ListNode *head) {
      ListNode* slow = head;
      ListNode* fast = head;
      while(slow && fast && fast->next){
         slow = slow->next;
         fast = fast->next->next;
         if(slow == fast)break;
      if(!fast || !fast->next)return NULL;
      if(slow == fast){
         slow = head;
            slow = slow->next;
            fast = fast->next;
      return slow;




tail connects to node index 1
Published on 03-Feb-2020 10:45:06