快慢指针法:
分别定义 fast 和 slow指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。
slow: x + y
fast: x + y + z +y
fast = 2 *slow
得: z = x
再求x的值:头结点和相遇节点同时出发一个指针,每次只走一个节点, 相遇即环形入口
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while((fast != nullptr) && (fast->next != nullptr)) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) { // 快慢指针相遇
ListNode* index1 = fast;
ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2; // 返回环的入口
}
}
return nullptr;
}
};