My accepted Java solution with O(n) time and O(1) space


  • 0
    R

    public class Solution {

    public boolean hasCycle(ListNode head) {

      if ((head == null) || (head.next == null)) 
        return false;
      ListNode slow = head;
      ListNode fast = head;
      
      while ((fast.next != null) && (fast.next.next != null)) {
        if ((fast.next == slow) || (fast.next.next == slow)) 
          return true;
        fast = fast.next.next;
        slow = slow.next;
      }
      return false;
    }
    

    }


Log in to reply
 

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