I don't know what's wrong with my C code【 Time Limit Exceeded】, I tested it on my computer and it works.


  • 0
    B
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    
    
    int linkNum(struct ListNode *head, struct ListNode *target)
    {
        int num = 0;
        struct ListNode *p = head;
        while (NULL!=p && target!=p)
        {
            p = p->next;
            ++num;
        }
        if (target == p)
        {
            return num;
    	}
        else
            return -1;
    }
    bool hasCycle(struct ListNode *head) {
        int num = 0;
        
        struct ListNode *q = head;
        while(NULL!=q)
        {
            if (num != linkNum(head,q))
            {
                return true;
            }
            else
            {
                q = q->next;
                ++num;
            }
        }
        return false;
    }

  • 0
    S

    why so long code

    use 2 pointer concept

    bool hasCycle(struct ListNode *head) {

    struct ListNode *p1,*p2;
    p1=p2=head;
    while(p2 && p2->next && p2->next->next ){
        p2=p2->next->next;
    
        p1=p1->next; 
         if(p1==p2)
            return true;
          
    }
    
        return false;
    

    }


Log in to reply
 

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