Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Last active June 29, 2019 16:12
Show Gist options
  • Save yangpeng-chn/b963a72ca96f6477c3a4ca22a8214c04 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/b963a72ca96f6477c3a4ca22a8214c04 to your computer and use it in GitHub Desktop.
Fast and Slow pointers
// start with different position
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode *slow = head;
ListNode *fast = head->next;
while(fast && fast->next){
if(slow == fast) return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
// start with same position
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment