Accepted clean Java solution

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

  • -3

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

  • 0

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

    In your case, let's start from the beginning, slow is 1, fast is 1, because fast != null and != null, we enter the while loop, now, slow is 2, and fast is null (, 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

    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.