What is the meaning of "{ },no cycle " input case in Linked List Cycle problem ??


  • 0
    M

    Here is my code

            class Solution {
        public:
            bool hasCycle(ListNode *head) {
                
            }
        };
    
    bool hasCycle(ListNode *head)
    {
        ListNode *p,*q,*r;
      
        p=head;
        q=head;
        while(p && q && q->next)
        {
            p=p->next;
            q=q->next->next;
            if(p==q)
                return true;
        
        }
            return false;            // condition when there is no loop
        
    }

  • 0
    S

    '{ },no cycle ' means there is no node in list. It cannot have cycle.

    The real hasCycle will never be called in above code.

    Either this way:

    class Solution {
    public:
        bool hasCycle(ListNode *head);
    };
    
    bool Solution::hasCycle(ListNode *head)
    {
        ListNode *p,*q,*r;
    
        p=head;
        q=head;
        while(p && q && q->next)
        {
            p=p->next;
            q=q->next->next;
            if(p==q)
                return true;
    
        }
            return false;            // condition when there is no loop
    
    }
    

    Or this way:

    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            ListNode *p,*q,*r;
        
            p=head;
            q=head;
            while(p && q && q->next)
            {
                p=p->next;
                q=q->next->next;
                if(p==q)
                    return true;
        
            }
            return false;            // condition when there is no loop
        }
    };
    

  • 0
    M

    if there will be no node, then head will be null. The above code which i posted is returning false on that.
    So why the test case is generating error??


  • 0
    S

    I updated my answer.


  • 0
    M

    Yep that helped,thanks! :)


Log in to reply
 

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