diff --git a/算法思维系列/双指针技巧.md b/算法思维系列/双指针技巧.md index cf5227d..f5edbd4 100644 --- a/算法思维系列/双指针技巧.md +++ b/算法思维系列/双指针技巧.md @@ -230,4 +230,25 @@ void reverse(int[] nums) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +[ryandeng32](https://github.com/ryandeng32/) 提供 Python 代码 +```python +class Solution: + def hasCycle(self, head: ListNode) -> bool: + # 检查链表头是否为None,是的话则不可能为环形 + if head is None: + return False + # 快慢指针初始化 + slow = fast = head + # 若链表非环形则快指针终究会遇到None,然后退出循环 + while fast.next and fast.next.next: + # 更新快慢指针 + slow = slow.next + fast = fast.next.next + # 快指针追上慢指针则链表为环形 + if slow == fast: + return True + # 退出循环,则链表有结束,不可能为环形 + return False +```