Java O(N) Solution using slow and fast pointers


  • 0
    R
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            ListNode slow = head, fast = head;
            if(head == null || head.next == null)
                return null;
            do{
                if(fast == null || fast.next == null){
                    return null;
                }
                else{
                    slow = slow.next;
                    fast = fast.next.next;
                }
            }while(slow != fast);
            slow = 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.