Leetcode – Linked List Cycle

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


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:

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:
String foo = "bar";
  • Tayyab

    This confuses me, what if there is a sixth element in the list that is looping to the third element?

    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?

  • ryanlr

    Thanks! fixed.

  • ryanlr

    Yes, deleted.

  • dd

    The naive version is wrong?

  • shadowlou

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