class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *left = head, *right = head;
while(right){
left = left -> next;
if(!right -> next)
return nullptr;
right = right -> next -> next;
if(left == right){
ListNode *temp = head;
while(left != temp){
left = left -> next;
temp = temp -> next;
}
return temp;
}
}
return nullptr;
}
};
Accepted
16/16 cases passed (8 ms)
Your runtime beats 73.11 % of cpp submissions
Your memory usage beats 98.77 % of cpp submissions (7.3 MB)