My 8ms C++ Solution

  • 0
     class Solution {
        ListNode *detectCycle(ListNode *head) {
            if (!head) return 0;
            ListNode *fast = head, *slow = head;
    		if (fast->next && fast->next->next)
    				fast = fast->next->next;
    				slow = slow->next;
    			}while (fast != slow && fast->next && fast->next->next);
                // the point is when two pointers meet, the distance from the position 
                // to the entry is equal to the distance from head to the entry
    			if (fast == slow)
    				for (fast=head; fast!=slow; fast=fast->next, slow=slow->next);
    				return fast;
    		return 0;

    Though I think 8ms should be a deviation...

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.