Java solution O(1) sapce


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

  • 0
    M

    Can you tell me how can you think of this ? it is so nice.


  • 0
    D

    @journey0408 that's cool, and it does not destroy the structure of the list. 'fast' travel two steps per time while 'slow' travel one step per time, if there is a cycle, 'fast' will meet 'slow'.


  • 0
    C

    great solution!


Log in to reply
 

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