> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/wan-quan-an-zhao-jiu-zhang-suan-fa-shua-de-60-dao-zuo-you/vi.-linked-list/141.-linked-list-cycle.md).

# 141. Linked List Cycle

{% hint style="success" %}

### key idea: fast and slow pointers

### 核心： 快慢指针

{% endhint %}

### Java example:

```java
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null) return false;
        ListNode slow = head, fast = head.next;
        while(fast != null && fast.next != null){
            if(fast == slow) return true;
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}
```

### Python example:

```python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        # edge case
        if head == None:
            return False
        
        # regular case
        slow = head
        fast = head.next
        while fast != None and fast.next != None:
            if fast == slow:  # fast.next == slow
                return True   # 想象fast 追 slow,总能追上的
            slow = slow.next
            fast = fast.next.next
            
        return False
```
