We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Cycle Detection
Cycle Detection
Sort by
recency
|
1359 Discussions
|
Please Login in order to post a comment
This cycle detection problem feels a lot like looping mechanics in Stardew Valley daily routines and repeating patterns. Using slow/fast pointers makes those cycles much easier to visualize.
bool has_cycle(SinglyLinkedListNode* head) { if (!head || !head->next) return false; SinglyLinkedListNode* turtle = head; SinglyLinkedListNode* hare = head; while (hare && hare->next) { hare = hare->next->next; turtle = turtle->next; if (hare == turtle) return true; } return false; }
Here is a solution for C++14:
There is not such good explaining about the input: First suposition: By considering the input as all elements beign the array, it only succeeds two cases. Second suposition: By considering input as {n0, item0, ... , itemn0, n1, item0, ... , itemn1, etc} it also fails.
Not sure how to process the input.
def has_cycle(head): slow = head fast = head