【141.环形链表】【Python】

This commit is contained in:
Ryan Deng
2020-11-10 22:58:31 -05:00
committed by labuladong
parent 8473c84f8d
commit 780a1c4661

View File

@ -230,4 +230,25 @@ void reverse(int[] nums) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
======其他语言代码======
[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
```