Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active March 26, 2022 16:11
Show Gist options
  • Save dgodfrey206/78fc870ab9b20df2c44e6eb4e846f516 to your computer and use it in GitHub Desktop.
Save dgodfrey206/78fc870ab9b20df2c44e6eb4e846f516 to your computer and use it in GitHub Desktop.
Remove a loop from a linked list
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;
}
}
}
@dgodfrey206
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment