142. Linked List Cycle II
题目描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Notice that you should not modify the linked list.
示例:
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
解题思路:(快慢指针)
设快指针和慢指针同时从头结点出发,快指针每次走两步,慢指针每次走一步。当快指针走环形m圈,慢指针走环形n圈后,两指针在紫色点处相遇。
快指针走过的距离: a + m ( b + c ) + b a+m(b+c)+b a+m(b+c)+b
慢指针走过的距离: a + n ( b + c ) + b a+n(b+c)+b a+n(b+c)+b
快指针的速度是慢指针的两倍,所以有: a + m ( b + c ) + b = 2 ∗ [ a + n ( b + c ) + b ] a+m(b+c)+b = 2*[a+n(b+c)+b] a+m(b+c)+b=2∗[a+n(b+c)+b]
即: a = ( m − 2 n ) ( b + c ) − b = ( m − 2 n − 1 ) ( b + c ) + c a=(m-2n)(b+c)-b=(m-2n-1)(b+c)+c a=(m−2n)(b+c)−b=(m−2n−1)(b+c)+c
m − 2 n m-2n m−2n为大于等于1的整数
当fast与slow相遇后,fast回到起始位置,slow仍留在第一次相遇的位置,fast与slow都以速度为1前进,第二次相遇点恰好在环的起始位置。(fast到达环的起始位置走过距离为a,此时slow也走了a,b+c 为一圈,slow绕环 m-2n-1 圈后剩下的距离为c,恰好到环的起点处。)
代码:
/**
* 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 *fast = head;
ListNode *slow = head;
while(fast!=nullptr && fast->next!=nullptr){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
fast = head;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
return nullptr;
}
};