mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-04 19:28:07 +08:00
【141.环形链表】【Python】
This commit is contained in:
@ -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
|
||||
```
|
||||
|
Reference in New Issue
Block a user