Q142. Linked List Cycle II
Last updated
Last updated
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head) return NULL;
ListNode* slow1 = head;
ListNode* slow2 = head;
ListNode* fast = head;
while(fast && fast->next){
fast = fast->next->next;
slow1 = slow1->next;
if(fast == slow1){
while(slow2 != slow1){
slow2 = slow2->next;
slow1 = slow1->next;
}
return slow2;
}
}
return NULL;
}
};