C++ Code:
void remove_loop(Node *head){
Node *slow = head;
Node *fast = head;
if (!head || !(head->next))
return;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
break;
}
// No Loop exixts
if (slow != fast){
std::cout << "No Loop" << std::endl;
return;
}
// When Loop exists
slow = head;
while(slow->next != fast->next){
slow = slow->next;
fast = fast->next;
}
fast->next = nullptr;
}
Detailed explanation is available on Youtube:
Subscribe to KnowledgeCenter
No comments:
Post a Comment