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

  • 0
    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(!=null &&!=null){ 
                slow =;
                fast =;
                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.