Java-InPlace-2 references


  • 1
    A

    Trick is to have two pointers starting from the head. The Fast pointers travels 2 nodes at a time and the Slow travels 1 node at a time. If there is a loop, they must meet at some time.

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

Log in to reply
 

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