题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
IDEA
借用别人的一个图来说明。
设置两个指针,slow每次走一步,fast每次走两步
X为链表投,Y为环的起点,Z为两个指针相遇位置
a为从头到环起点的距离,b+c等于环长l
则有: 2(a+b)=a+b+n(b+c)
=> a=(n-1)b+nc=(n-1)(b+c)+c=(n-1)l+c
即让一个指针在X,一个指针在Z点(两个指针速度相同),第一个指针走a距离,等于第二个指针走过c加(n-1)个环长,最终早Y点相遇,即环的起点
CODE
/**
* 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==NULL)
return NULL;
ListNode *slow=head,*fast=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return fast;
}
}
return NULL;
}
};