142. Linked List Cycle II

ss
Mar 14, 2021

--

這題跟 287. Find the Duplicate Number一樣, 就不再說明了


class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head|| !head->next || !head->next->next) return nullptr;
ListNode *fast = head->next->next;
ListNode *slow = head->next;
while(fast != slow && fast != nullptr && fast->next && fast->next->next){
fast= fast->next->next;
slow = slow->next;

}
if (fast != slow) return nullptr;
fast = head;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
};

--

--

ss
ss

No responses yet