您的位置:首页 > 其它

[LeetCode] Linked List Cycle II Solution

2014-11-03 07:55 288 查看
Given a linked list, return the node where the cycle begins, if there is no cycle, return null.

Follow up: could you solve it without using extra space?

Ideas:

1. Check whether the linked list has cycle, use slow and fast pointer. ([LeetCode] Linked List Cycle) 

2.  if has, then,

Assume slow pointer goes n steps, then, fast pointer goes 2n steps. 

Assume head to cycle starter are m steps,  then 2n = length +  (n - m), 

So, n = length  - m; m = length -  n

So. flow the fast pointer,  Slow pointer to the starter is the same length between the head to starter

/**
* 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) {
if(!head) return head;
if(head->next == NULL) return NULL;

ListNode
*pSlow = head,
*pFast = head;

//get the node which slow and fast encounter
while(pFast!= NULL && pFast->next != NULL)
{
pSlow = pSlow->next;
pFast = pFast->next->next;

if(pFast == pSlow)
{
break;
}
}

//if encouter, pSlow go n step, pFast go 2n step.
// if head to the starter is m step, list's length is length
// then 2n = length + (n - m)
//So. length = n + m; n = length - m; m = length - n;
// Slow pointer to the starter is the same length between the head to starter
if(pFast== pSlow)
{
pFast = head;
//let pFast encounter pSlow again.
// this node is the starter of cycle
while(pFast != pSlow)
{
pFast = pFast->next;
pSlow = pSlow->next;
}

return pSlow;
}

return NULL;
}

private:
bool hasCycle(ListNode *head) {
if(!head) return false;
if(head->next == NULL) return false;

ListNode
*pSlow = head,
*pFast = head;

while(pFast!=NULL && pFast->next !=NULL)
{
pSlow = pSlow->next;
pFast = pFast->next->next;

if(pSlow == pFast)
{
return true;
}
}

return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode List