Leetcode – Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Analysis

If we have 2 pointers - fast and slow. It is guaranteed that the fast one will meet the slow one if there exists a circle.

The problem can be demonstrated in the following diagram:
linked-list-cycle

Java Solution

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
 
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
 
            if(slow == fast)
                return true;
        }
 
        return false;
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. shadowlou on 2014-7-27

    The first two if statements are already included in the third one.

  2. dd on 2014-12-24

    The naive version is wrong?

  3. ryanlr on 2015-6-4

    Yes, deleted.

  4. ryanlr on 2015-6-7

    Thanks! fixed.

  5. Tayyab on 2016-7-24

    This confuses me, what if there is a sixth element in the list that is looping to the third element?
    A->B->C->D->E->B

    fast will never reach the second B and the loop will terminate without detecting the loop.
    This solution is on so many sites, why can’t people see it?
    Or may be I’m catching something wrong?

  6. Carlos Gomez on 2016-8-16

    Does this make sense?

    A -> B -> C -> D -> E -> B

    iter 1
    S = A
    F = C

    iter 2
    S = B
    F = E

    iter 3
    S = C
    F = C

    Cycle detected, return true

  7. tm on 2016-8-17

    If you compare two nodes using boolean operators will it return the correct value? Shouldn’t you implement your own equal method for nodes?

  8. Tayyab on 2016-10-20

    After F=E, how does it get to C again, if it’s skipping to the end of the list?
    And even if it is starting form the beginning again, shouldn’t it again jump to A instead of C?

  9. Vani on 2017-3-1

    Since it is cycle , next iternation, F jumps by skipping one element. So it skips, B and then goes to C. Remember that E connects back to B and next of E is B, next of B is C.

  10. Tayyab on 2017-3-2

    Oh yes, the two B’s are the same node! That is what I was skipping.
    Thank you so much! This bugged me for a long time.

Leave a comment

*