Using small trick by catch NullPointerException

  • 1

    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 =;}              // if NullPointerException happen, which mean there is no circle
                catch(Exception e)    {return false;}
                slower =;
                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.