# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
def hasCycle(self , head: ListNode) -> bool:
if not head:#如果是空链表
return False
fast, slow = head, head#快、慢指针
while slow and fast:
slow = slow.next#慢指针每次前进一步
if fast.next:#快指针每次前进两步(若允许)
fast = fast.next.next
else:#如果快指针到达了链表末尾,无环
return False
if slow==fast:#快慢指针相遇,有环
return True
return False#如果快指针到达了链表末尾,无环



京公网安备 11010502036488号