My easy 12ms C++ solution sharing.


  • 14
    R
    bool hasCycle(ListNode *head) 
    {
        ListNode *fast;
        fast = head;
        while (head)
        {
            head = head->next;
            if (fast->next && fast->next->next)
                fast = fast->next->next;
            else
                return false;
                
            if (fast == head)
                return true;
        }
        
        return false;
    }

  • 0
    S

    What if cycle present in places other than head ?
    Eg: 1->2->3->4->2.


  • 0
    R

    it still works, for you example: 1->2->3->4->2:

    iteration, head, fast

    1       ,      2        3
    
    2       ,      3        2
    
    3       ,      4        4  ( return true)

Log in to reply
 

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