Concise solution


  • 0
    R
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) 
        {
            ListNode *fast = head;
            ListNode *slow = head;
            
            while (slow)
            {
                slow = slow->next;
                if (fast && fast->next)
                {
                    fast = fast->next->next;
                }
                else 
                    return NULL;
                
                if (slow == fast)
                    break;
            }
            
            slow = head;
            while (slow != fast)
            {
                slow = slow->next;
                fast = fast->next;
            }
            
            return fast;
        }
    };

Log in to reply
 

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