Method 1: (Hashing)
bool detect_loop_map(Node *head){
std::unordered_map<Node*, bool> visited;
Node *curr = head;
while(curr){
if (visited[curr] == true)
return true;
visited[curr] = true;
curr = curr->next;
}
return false;
}
Method 2:(Floyd's Cycle Detection)
bool detect_loop_floyd(Node *head){
Node *slow = head;
Node *fast = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if (slow == fast){
return true;
}
}
return false;
}
Watch detailed explanation on Youtube:
Watch detailed explanation on Youtube:
Visit our Youtube playlist for Linked List: https://www.youtube.com/playlist?list=PL1w8k37X_6L-bwZCPpELH6Cwo3WzUxDp7
Subscribe to KnowledgeCenter
Subscribe to KnowledgeCenter
Thanks for sharing the video link.
ReplyDeletehttps://www.youtube.com/c/KnowledgeCenter?sub_confirmation=1
ReplyDelete