Why this code is not able to remove the loop as i did same as explained

void removeLoop(Node* head)
{
    if (head == NULL)
        return;
    Node *slow, *fast;
    slow = head;
    fast = head;
    while (fast != NULL && fast->next != NULL)
    {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast)
            break;
    }
    slow = head;
    Node *prev = fast;
    while (fast != NULL && fast->next != NULL)
    {
        slow = slow->next;
        fast = fast->next;
        if (slow == fast)
        {
            prev->next = NULL;
            break;
        }
        prev = fast;
        
    }
}

Hi @pks101295

In your code please check these cases,

  1. in base case, if head-> next == NULL then also return
  2. start fast with head->next
  3. after first while loop, check the condition for no cycle
    if (fast == NULL || fast->next == NULL){ //No cycle present
    return ;
    }
  4. and after first while loop, if it’s a full cycle then you can break the cycle there only,

if (fast->next == head)
{
fast->next = NULL;
return true;
}

Thanks @sanjeetboora