Simple and easy to understand C solution


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

Log in to reply
 

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