Share a 8 line C solution


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode *head) {
        struct ListNode *fast=head,*slow=head;
        while(fast && fast->next && fast->next->next)
        {
            fast = fast->next->next;
            if(fast->val == slow->val) return true;
            slow = slow->next;
        }
        return false;
    }

  • 0
    K

    why fast->val == slow->val then there has a cycle?


  • 0
    M

    Maybe he thinks all the nodes have distinct values, I think it's OK to change it into (fast == slow) to compare the pointer.


Log in to reply
 

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