C++ Code:
void find_loop_beginning(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 != fast){
slow = slow->next;
fast = fast->next;
}
std::cout << "First loop element = " << slow->data << std::endl;
}
Detailed explanation can be found on Youtube:
Subscribe to KnowledgeCenter
No comments:
Post a Comment