sundeepblue
2/11/2014 - 8:01 PM

detect the starting node for a loop or cycle in linked list

detect the starting node for a loop or cycle in linked list

node* find_loop_start(node *head) {
    	if(!head || !head->next) return NULL;
	node *slow = head, *fast = head;
	while(slow && fast && fast->next) {
		slow = slow->next;
		fast = fast->next->next;
		if(slow == fast) break;
	}
	if(fast->next == NULL)  // no loop, 4/30/2014, add this check for early return if no loop.
		return NULL;
	fast = head;
	while(fast != slow) {
		fast = fast->next;
		slow = slow->next;
	}
	return fast;
}