Last active
June 29, 2019 16:12
-
-
Save yangpeng-chn/b963a72ca96f6477c3a4ca22a8214c04 to your computer and use it in GitHub Desktop.
Fast and Slow pointers
This file contains 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
// 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