详细
快慢指针法,快指针是慢指针的俩倍,如果有环,一定会在环中相遇。而相遇的位置到环入口节点的距离和头结点到入口节点的位置一定相同。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == nullptr) return nullptr;
ListNode* slow = head;
ListNode* fast = head;
ListNode* now = head;
while(1){
if(slow->next == nullptr || fast->next == nullptr || fast->next->next == nullptr){
return nullptr;
}
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
while(now != slow){
now = now->next;
slow = slow->next;
}
return now;
}
};