Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 25, 2018 05:30
Show Gist options
  • Save kanrourou/fbefc2863b64d697c5da6d673752bfa0 to your computer and use it in GitHub Desktop.
Save kanrourou/fbefc2863b64d697c5da6d673752bfa0 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
auto fast = head, slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(slow == fast)break;
}
if(!fast || !fast->next)return nullptr;
fast = head;
while(slow != fast)
{
fast = fast->next;
slow = slow->next;
}
return slow;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment