Java solution O(1) sapce

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

  • 0

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

  • 0

    @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

    great solution!

Log in to reply

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