Simple O(n) time O(1) space java solution


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

Log in to reply
 

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