18ms, c++, using fast/slow pointers


  • 0
    D
    class Solution 
    {
    public:
        bool hasCycle(ListNode *head) 
        {
            if (!head)
            {
                return false;
            }
    
            ListNode* f = head->next;
            ListNode* s = head;
    
            while (s != f)
            {
                if (f && f->next)
                {
                    f = f->next->next;
                }
                else
                {
                    return false; // Reached the end of the list therefore no cycle.
                }
    
                s = s->next;
            }
    
            return true;
        }
    };

Log in to reply
 

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