Accepted clean Java solution


  • 4
    public boolean hasCycle(ListNode head) {
      ListNode slow = head, fast = head;
      
      while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        
        if (slow == fast) 
            return true;
      }
      
      return false;
    }

  • -3
    Q

    there is little null pointer exception in your code.
    when the list is [1,2] no cycle, fast.next.next = null and the program will throw exception.


  • 0

    "while (fast != null && fast.next != null)" makes sure that we can safely access fast.next.next.

    In your case, let's start from the beginning, slow is 1, fast is 1, because fast != null and fast.next != null, we enter the while loop, now, slow is 2, and fast is null (1.next.next), so it exits the while loop and return false.

    So there shouldn't be any null exception. The technique I use is a classic way to make the fast pointer move 2 steps forward each time.


  • 0
    C

    Agreed. Didn't see any NPE. Correct me if I am wrong. :D


Log in to reply
 

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