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;
}
}
Why this code is not able to remove the loop as i did same as explained
Hi @pks101295
In your code please check these cases,
- in base case, if head-> next == NULL then also return
- start fast with head->next
- after first while loop, check the condition for no cycle
if (fast == NULL || fast->next == NULL){ //No cycle present
return ;
} - 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;
}