Java Perfect, Clean Code, O(N) Time Solution


  • 0
    H
    public ListNode detectCycle(ListNode head) {
            ListNode fast = head, slow = head;
    		while(fast != null && fast.next != null){
    			slow = slow.next;
    			fast = fast.next.next;
    			if(slow == fast){ //There is a cycle
    			
    				//Finds the start of the cycle
    				slow = head;
    				while(slow != fast){
    					slow = slow.next;
    					fast = fast.next;
    				}
    				return slow;
    			}
    		}
    		return null; //No cycle
        }
    

Log in to reply
 

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