Monday, February 21, 2022

LeetCode 142. Linked List Cycle II

https://leetcode.com/problems/linked-list-cycle-ii/
/**
* 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;
auto slow = head;
auto fast = head;
// Two Pointer
// meet: slow & fast
while(fast and fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
// not cycle
if(!fast or !fast->next) return NULL;
// meet: head & slow
while(head != slow){
slow = slow->next;
head = head->next;
}
return head;
}
};

No comments:

Post a Comment