提交 780a1c46 编写于 作者: R Ryan Deng 提交者: labuladong

【141.环形链表】【Python】

上级 8473c84f
......@@ -230,4 +230,25 @@ void reverse(int[] nums) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ 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
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册