Java Clean Solution


  • 4
    C
    public class Solution {
        /**
         * @param head: The first node of linked list.
         * @return: The node where the cycle begins. 
         *           if there is no cycle, return null
         */
        public ListNode detectCycle(ListNode head) {  
            // write your code here
            if(head == null) return null;
            ListNode slow = head, fast = head;
            do{
                if(fast == null || fast.next == null) return null;
                slow = slow.next;
                fast = fast.next.next;
                
            }while(slow != fast);
            fast = head;
            while(slow != fast){
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
    }

Log in to reply
 

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