Leetcode原题 022
思路:
快慢指针法:定义fast,slow 两个指针,从头开始遍历。
是否有环:
fast每次走2格,slow每次走1格。
所以如果fast能走到NULL或者fast->next==NULL,说明没有环(fast比slow走的快)
如果有环,在进入环后,由于fast对于slow相对速度为1,所以它们一定会相遇。
相遇时,进入找入口环节。
找到环入口:
将两个指针的速度均设置为slow,也就是每次前进一格。记作index1,index2;
环中相遇位置为fast==slow时,即fast。
index1=head//从头出发;
index2=fast//从相遇位置出发
当index1==index2时,它们在入口处相遇,只不过index2是在环内转了n圈。index1走的是直线。//这个可以用数学证明。
代码如下
ListNode* detectCycle(ListNode* head) {
ListNode* fast;
ListNode* slow;
fast = head;
slow = head;
if (fast==NULL||fast->next == NULL) {
return NULL;
}
while (fast!=NULL&&fast->next!=NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
break;
}
}
if (fast==NULL||fast->next == NULL) {
return NULL;
}
slow = head;
while (slow!=fast) {
fast = fast->next;
slow = slow->next;
}
return slow;
}