Using small trick by catch NullPointerException


  • 1
    F

    if NullPointerException happens, which means no circle. Thus, you don't need to consider the disgusting nullPointerException of the faster node;

    public class Solution {
        public boolean hasCycle(ListNode head) {
            ListNode faster = head;
            ListNode slower =head;        
            while(slower != null || faster!= null){
                try {faster = faster.next.next;}              // if NullPointerException happen, which mean there is no circle
                catch(Exception e)    {return false;}
                slower = slower.next;
                if(faster == slower)
                    return true;
            }
            return false;
        }
    }

Log in to reply
 

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