> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-11-2022-141.md).

# 01/11/2022 141

Approach 1:

using HashSet to test if it has the same node inside it, otherwise add the node inside the hashSet, set head = head.next.

Time O(n) Space O(n)

public class Solution {&#x20;

public boolean hasCycle(ListNode head) {

&#x20;       &#x20;

```
   if(head == null) return false;
     //using HashSet
    HashSet<ListNode> set = new HashSet<>();
    
    while(head != null){
        if(set.contains(head)){
            return true;
        }
        
        set.put(head);
        head = head.next;
    }
    
    
    
    return false;
```

}

}

Approach 2:

using Floyd's cycle detection algorithm to check if there is a circle in the linkedlist. Using two pointers, one is slow, 1 step per time. Another is fast, 2 steps per time. these two pointers equal, then it has circle.

Time O(n)

Space O(1)

```
 public boolean hasCycle(ListNode head) { 
    if(head == null) return false;
    ListNode slow = head;
    ListNode fast = head;
    
    while(fast.next!=null && fast.next.next!=null) {
    slow = slow.next;
    fast = fast.next.next;
    if(slow==fast) return true;
}
return false;
}
```
