# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
def hasCycle(self , head ):
# write code here
if not head:
return False
slow, fast = head, head
while 1:
if fast and fast.next: #没有环的情况下,保证fast最后停在none
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
else:
return False
判断链表中是否有环
最新推荐文章于 2025-03-17 11:02:22 发布
该篇博客探讨了如何使用Python实现一个检测链表中是否存在循环的算法。通过设置两个指针,一个慢指针每次移动一步,快指针每次移动两步,当快指针追上慢指针时,表明链表存在环。若快指针到达None,则链表无环。此方法简洁而高效。
478

被折叠的 条评论
为什么被折叠?



