103. Linked List Cycle II
ListNode * detectCycle(ListNode * head) {
// write your code here
if(head == NULL){
return head;
}
ListNode *slow = head;
ListNode *fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
break;
}
}
if(fast == NULL || fast->next == NULL){
return NULL;
}
while(head != slow){
head = head->next;
slow = slow->next;
}
return head;
}
Comments
Post a Comment