Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
Note: Do not modify the linked list.
Thousands of articles to introduce this idea. This is really very neat.
ListNode *detectCycle(ListNode *head) {
if(!head) return NULL;
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
break;
}
}
if(!fast || !fast->next || !fast->next->next) return NULL; // remember to check the no circle condition.
slow = head;
while(slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
374

被折叠的 条评论
为什么被折叠?



