Skip to content

Commit 780a1c4

Browse files
ryandeng32labuladong
authored andcommitted
【141.环形链表】【Python】
1 parent 8473c84 commit 780a1c4

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

算法思维系列/双指针技巧.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,4 +230,25 @@ void reverse(int[] nums) {
230230
<img src="../pictures/qrcode.jpg" width=200 >
231231
</p>
232232

233-
======其他语言代码======
233+
======其他语言代码======
234+
235+
[ryandeng32](https://github.com/ryandeng32/) 提供 Python 代码
236+
```python
237+
class Solution:
238+
def hasCycle(self, head: ListNode) -> bool:
239+
# 检查链表头是否为None,是的话则不可能为环形
240+
if head is None:
241+
return False
242+
# 快慢指针初始化
243+
slow = fast = head
244+
# 若链表非环形则快指针终究会遇到None,然后退出循环
245+
while fast.next and fast.next.next:
246+
# 更新快慢指针
247+
slow = slow.next
248+
fast = fast.next.next
249+
# 快指针追上慢指针则链表为环形
250+
if slow == fast:
251+
return True
252+
# 退出循环,则链表有结束,不可能为环形
253+
return False
254+
```

0 commit comments

Comments
 (0)