Java Solution by Catching NullPointerException


  • -1
    E
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head==null) return false;
            if(head.next==null) return false;
            if(head.next.next==head) return true;
            if(head.next.next==null) return false;
            ListNode fast = head;
            ListNode slow = head;
            
            try{
                while(true){
                    slow = slow.next;
                    fast = fast.next.next;
                    if(slow==fast) return true;
                }
            }catch(NullPointerException e){
                return false;
            }
            
        }
    }

Log in to reply
 

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