// 思路:快慢指针 + 回拨指针到头节点
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL || head->next == NULL) {
return NULL;
}
auto slow = head;
auto fast = head;
while(slow && fast) {
slow = slow->next;
fast = fast->next;
if (fast)
fast = fast->next;
if (slow == fast)
break;
}
if (fast == nullptr) {
return nullptr;
}
auto headA = slow;
while(headA != head) {
headA = headA->next;
head = head->next;
}
return headA;
}
};