Skip to content

Instantly share code, notes, and snippets.

@pwxcoo
Last active June 18, 2019 01:31
Show Gist options
  • Save pwxcoo/b676c2053716930570b39ea730791e75 to your computer and use it in GitHub Desktop.
Save pwxcoo/b676c2053716930570b39ea730791e75 to your computer and use it in GitHub Desktop.
Find Cycle List Beginning Node
/**
* Time: O(n)
* Space: O(1)
* 1. find list if exists cycle.
* 2. 0 -> a(cycle s) -> b(cycle met) -> c(cycle s(e))
* slow = a + b + (b + c)n1, fast = a + b + (b + c)n2.
* slow * 2 = fast
* 2a + 2b + 2*n1*(b + c) = a + b + n2*(b + c) => a = (n2 - 2*n1) * (b + c) - b
* After meeting, so one start going from head and meanwhile slow start going, they will meet at cycle begin.
**/
ListNode *detectCycle(ListNode *head) {
if (!head) return NULL;
ListNode *slow = head;
ListNode *fast = head;
bool flag = false;
while(fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
flag = true;
break;
}
}
if (!flag) return NULL;
fast = head;
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
@pwxcoo
Copy link
Author

pwxcoo commented Sep 12, 2018

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