题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
判断一个链表是否存在环路,若存在环路则返回环路的起始位置。要求不改变链表,且不用额外申请空间。
思路:
如果你做过Linked List Cycle I 的话肯定能立马想到two point的思路能够找到一个链表是否有环路,本题的难点在于如何找到环路的起点,其实也和two point有关。简单说一下思路:
设置两个指针,一个慢指针slow_point,一个快指针fast_point。其中slow_point每次只向前移动一次,fast_point每次向前移动两次。那么当链表中存在环路时,必然会出现slow_point==fast_point的情况,如下图所示,X是链表的起点,Y是环路的起始点,Z是两个指针相遇的点:
由于两个指针相遇,那么快指针走的路程是慢指针的两倍,所以有:2(a+b)=a+b+c+b,那么a+b=b+c,进一步有a=c,所以此时将慢指针指回原点,然后让两个指针每次往前走一步,它们一定会在Y相遇,这样就找到了环路的起点。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==nullptr)
return nullptr;
ListNode *l1=head;//slow_point
ListNode *l2=head;//fast_point
bool isCycle=false;
while((l1!=nullptr && l2!=nullptr))
{
l1=l1->next;
if(l2->next!=NULL)
l2=l2->next->next;
else
l2=NULL;
if(l1==l2)
{
isCycle=true;
break;
}
}
if(!isCycle) return NULL;
l1 = head;
while( l1 != l2) {
l1 = l1->next;
l2 = l2->next;
}
}
};
结果: