题目:
代码(首刷看解析 2024年1月13日):
cpp
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == nullptr) return nullptr;
ListNode* fast = head;
ListNode* slow = head;
while (true) {
if(fast->next == nullptr || fast->next->next == nullptr) return nullptr;
fast = fast->next->next;
slow = slow->next;
if(fast == slow) break;
}
fast = head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
双指针解决百分之99的链表题