Why my solution return a run time error??


  • 0
    Z
    bool hasCycle(ListNode *head) {
            if(head==NULL ||head->next==NULL) return false;
            ListNode* slow=head;
            ListNode* fast=head;
            while(slow->next && fast->next->next){
                slow=slow->next;
                fast=fast->next->next;
                if(fast==slow) return true;
            }
            return false;
        }
    

    The problem occurs at line 5. why while(slow->next && fast->next->next) returns error but while(fast->next && fast->next->next) works??


  • 1
    Y
    public boolean hasCycle(ListNode head){
    	if(head==null||head.next==null) return false;
    	ListNode point1=head,point2=head.next;
    	while(point1.next!=null&&point2.next!=null&&point2.next.next!=null){
    		if(point2.next==point1) return true;
    		point1=point1.next;
    		point2=point2.next.next;
    	}
    	return false;
    }

  • 2
    M

    Generally:

    Builtin operators && and || perform short-circuit evaluation (do not
    evaluate the second operand if the result is known after evaluating
    the first).

    Specifically:

    while(fast->next && fast->next->next) //right
    

    If the first statement(fast->next) is NULL, it will ignore the second one(fast->next->next).

    while(slow->next && fast->next->next) //wrong
    

    If slow->next is not NULL, fast->next->next will get error when fast->next is NULL. Actually, you don't need to care about slow, because it's covered by fast.

    More:

    while(fast->next->next && fast->next) //wrong
    

Log in to reply
 

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