Linked List Cycle I C++ simple solution
// Elharem Soufiane
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
	
        // If the list is empty or has one single node
        if(head == NULL || head->next == NULL) return NULL;
        ListNode *slow_pointer = head, *fast_pointer = head;
		
        // Move the slow_pointer by one and the fast_pointer by two
        slow_pointer = slow_pointer->next;
        fast_pointer = fast_pointer->next->next;
		
        // Searching for the cycle
        while(fast_pointer && fast_pointer->next) {
            if(slow_pointer == fast_pointer) break;
            slow_pointer = slow_pointer->next;
            fast_pointer = fast_pointer->next->next;
        }
		
         // If there's no cycle
        if(slow_pointer != fast_pointer) return NULL;
		
        // Initializing slow_pointer to head and letting fast pointer be at its position. 
        slow_pointer = head;
        while(fast_pointer != slow_pointer) {
		
            // Moving both slow_pointer and fast_pointer one node at a time. 
            slow_pointer = slow_pointer->next;
            fast_pointer = fast_pointer->next;
        }
		
        // The point at which they meet is the start of the loop.
        return slow_pointer;
    }
};

Follow me on Github.

Comments (1)