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


  • 1
    R

    public class Solution {

    public ListNode detectCycle(ListNode head) {
    
        if ((head == null) || (head.next == null)) 
          return null;
        ListNode slow;
        ListNode fast;
        
        slow = head;
        fast = head;
        
        while ((fast.next != null) && (fast.next.next != null)) {
          fast = fast.next.next;
          slow = slow.next;
          if (fast == slow) 
            break;
        }
        if ((fast.next == null) || (fast.next.next == null))
          return null;
        else {  
          fast = head;
          while (fast != slow) { 
            fast = fast.next;
            slow = slow.next;
          }
          return fast;
        }  
    }
    

    }


Log in to reply
 

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