Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
算法思想:
一指针以速度1向后遍历,一指针以速度2向后遍历,若相遇说明有回路,然后一指针从相遇点开始向后速度为1,一指针跳到头指针,以速度为1向后遍历,到相遇时即为循环开始点。
证明:如图所示,设p、q从O点出发p以速度1向后走,q以速度2向后走,因为存在环,所以毕定p与q会相遇,设相遇点为A,此时q走的总共距离Sq为p走的距离Sp的两倍,从图中可以看出,Sq-Sp表示的是q比p以A点为起点绕环走多绕的环的长度,是环长度的整数倍。也就是说,p从起点O走到A(中间有可能绕环走n圈)是环长度的整数倍。那么当p从头开始以速度1走,q从A以速度1走,那么当p走到A时,q必然走到A,因为速度一致,所以当它们第一次遇见时,即是循环的开始点。
/**
* 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 *p=head;
ListNode *q=head;
do{
if(p==NULL||q==NULL)return NULL;
p=p->next;
q=q->next;
if(q==NULL)return NULL;
q=q->next;
}while(p!=q);
p=head;
while(p!=q){
p=p->next;
q=q->next;
}
return p;
}
};
这里还有一个很好理解的方法,虽然由于破坏了整条链表而造成答案不正确,但是此一时彼一时嘛,在可以破坏链表的条件下,此方法更优
思想:每次走过一个节点时,将此节点的next指针指向自己,(为什么不指向NULL?因为如果没有环就无法判断了),一直向后走,如果带环,当遇到下一节点指向的就是自己本身时,即为循环开始点。
class Solution{
public:
ListNode *detectCycle(ListNode *head){
//if(head==NULL)return NULL;
ListNode *p=head;
while(p!=NULL){
ListNode *t=p->next;
if(p->next==p)return p;
p->next=p;
p=t;
}
return NULL;
}
};