Last active
March 26, 2022 16:11
-
-
Save dgodfrey206/78fc870ab9b20df2c44e6eb4e846f516 to your computer and use it in GitHub Desktop.
Remove a loop from a linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool has_cycle(node* head) { | |
if (!head || !head->next) return false; | |
node* slow, *fast; | |
slow = fast = head; | |
while (true) { | |
slow = slow->next; | |
if (fast->next) | |
fast = fast->next->next; | |
if (slow == nullptr || fast == nullptr) | |
return false; | |
if (slow == fast) { | |
return slow->next != nullptr; | |
} | |
} | |
} | |
void remove_cycle(node* head) { | |
if (!head || !head->next) return; | |
node* slow, *fast; | |
slow = fast = head; | |
while (true) { | |
slow = slow->next; | |
if (fast->next) | |
fast = fast->next->next; | |
if (slow == fast) { | |
if (slow != nullptr) | |
slow->next = nullptr; | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The loop is always located at the tail of the list. The trick is to move the fast pointer first before checking if both pointers are the same.