Java Solution (Floyd); ~O(n) running time, O(1) memory, 1ms.


  • 0
    S
    public class Solution {
      public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
    
        ListNode s = head;
        ListNode f = head.next.next;
    
        while (s != null && f != null) {
          if (s.val == f.val) return true;
          if (f.next == null) return false;
          s = s.next;
          f = f.next.next;
        }
    
        return false;
      }
    }
    

Log in to reply
 

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