方法一 活用set
ListNode *detectCycle(ListNode *head) {
set<ListNode *> save;
while (head != nullptr)
if (save.find(head) != save.end())
return *save.find(head);
else {
save.emplace(head);
head = head->next;
}
return nullptr;
}
方法二 快慢指针
ListNode *detectCycle(ListNode *head) {
if(head==nullptr)
return nullptr;
ListNode *slow = head, *fast = head;
while(true){
if(fast->next==nullptr||fast->next->next==nullptr)
return nullptr;
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
while(head!=fast){
head=head->next;
fast=fast->next;
}
return head;
}
}
}