题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
思路:快慢指针的使用。首先,first为快指针,每次只走一步;second为慢指针,每次走两步;快慢指针同时开始遍历,当快慢指针相等时,说明有环。并且,假设链表开始到环起点长为 s,环长为 l;当second走到begin时,first走到了s%l的位置,相对于环上;first于second相距为l-s%l,当first于second在环上相遇时,second走到了l-s%l的距离,因为每次可以拉近一个距离;这时third开始从头遍历,first于third相遇时,third走过s,first走过s%l,相对于环,first到了l-s%l+s%l,也就是l的地方,既begin;这就是环的起始点。
class Solution {
public:
ListNode *detectCycle(ListNode *head)
{
ListNode* fhead=new ListNode(1);
if(head==NULL) return NULL;
fhead->next=head;
ListNode * h1=fhead;
ListNode * h2=fhead;
do
{
if(h1->next!=NULL&&h1->next->next!=NULL)
{
h1=h1->next->next;
}
else
{
return NULL;
}
h2=h2->next;
}
while(h1!=h2);
ListNode* h3=fhead;
do
{
h1=h1->next;
h3=h3->next;
}
while(h1!=h3);
return h3;
}
};
本文介绍了一种利用快慢指针来寻找链表中环的起始节点的方法。通过两个速度不同的指针遍历链表,当它们相遇时,再从头节点出发一个新指针与相遇点的指针同步前进,最终相遇点即为环的起始位置。
374

被折叠的 条评论
为什么被折叠?



