> For the complete documentation index, see [llms.txt](https://longxingtan.gitbook.io/mle-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://longxingtan.gitbook.io/mle-interview/01_leetcode/02_linked_list/141.-linked-list-cycle.md).

# 141. Linked List Cycle

<https://leetcode.com/problems/linked-list-cycle/>

## solution

```python
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if head is None or head.next is None:
            return False

        slow = head
        fast = head.next
        while fast is not None and fast.next is not None:
            if slow == fast:
                return True

            slow = slow.next
            fast = fast.next.next

        return False
```

时间复杂度：O(n)\
空间复杂度：O(1)

## follow up

* SPFA 判断是否有负环

```python
import collections
n, m = map(int, input().split())

g = collections.defaultdict(list)
st = [True for i in range(n+1)]
dist = [0 for i in range(n+1)]
cnt = [0 for i in range(n+1)]

for i in range(m):
    a, b, w = map(int, input().split())
    g[a].append([b, w])

def spfa():
    q = [i for i in range(n+1)]
    while len(q) != 0:
        a = q.pop()  ## 这里要注意 如果用pop(0) 会超时，这是因为 Python中 pop(0)复杂度O(n),pop()是O(1)
        st[a] = False
        for b, w in g[a]:
            if dist[b] > dist[a] + w:
                cnt[b] = cnt[a] + 1
                if cnt[b] >= n:
                    return True
                dist[b] = dist[a] + w
                if st[b] == False:
                    q.append(b)
    return False

print("Yes" if spfa() else "No")
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/02_linked_list/141.-linked-list-cycle.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
