# 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
# 慢指针。
slow = head
# 快指针。
fast = head
# 判断fast.next用于防止无环的时候数组越界。
while fast and slow and fast.next:
# 慢指针一次走一步。
slow = slow.next
# 快指针一次走两步,则在有环的情况下快指针总会追上慢指针。
fast = fast.next.next
if fast == slow:
return True
return False

京公网安备 11010502036488号