Java solution Time O(n), space O(1), no change on original list


  • 0
    A
    public boolean hasCycle(ListNode head) {
            if(head == null){
                return false;
            }
            ListNode slow = head; // slow pointer runs 1 step ahead
            ListNode fast = head; // fast pointer runs 2 steps ahead
            
            while( fast.next!=null && fast.next.next!=null){ 
                slow = slow.next;
                fast = fast.next.next;
                if(slow == fast){ // if slow and fast pointer eventually run into each other, there must be a cycle
                    return true;
                }
            }
            return false;
        }
    

Log in to reply
 

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