您的位置:首页 > 其它

142. Linked List Cycle II

2018-03-04 12:30 316 查看
判断链表中是否有环,以及环开始的节点:
第一步,利用快慢指针法,判定是否有环,并返回快慢指针相遇的节点;
第二步,从快慢指针相遇的节点出发,继续单步遍历链表,记录单步执行次数,当再次回到该相遇节点时,单步遍历次数即为环的长度;
第三步,沿用快慢指针法,快指针先走环长度的步数,之后,快慢指针继续单步遍历,快慢指针相遇的节点即为环的开始节点。/**
* 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) {
ListNode *flag=hasCycle(head); //the meeting node

if(flag==NULL)
return NULL; // no cycle

ListNode *link=flag->next;;
int res=1;
while(link!=flag)
{
res++;
link=link->next;
} // res means the length of the cycle

ListNode *low=head;
ListNode *fast=head;
for(int i=0;i<res;i++)
fast=fast->next; //fast goes res steps

while(low!=fast)
{
low=low->next;
fast=fast->next;
} //the meeting node refers to the beginning node of the cycle
return low;
}

ListNode *hasCycle(ListNode *head)
{
if(head==NULL)
return NULL; // no cycle

ListNode *low=head;
ListNode *fast=head;

while(low!=NULL&&fast!=NULL)
{
low=low->next; // one step

for(int i=1;i<3;i++)
{
if(fast==NULL)
return NULL;
else
{
fast=fast->next;
}
} // two steps

if(low==fast)
return low;
}

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