classSolution:defhasCycle(self, head: Optional[ListNode])->bool:ifnot head or head.nextisNone:returnFalse
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.nextif fast == slow:returnTruereturnFalse
方法二:链表计数
classSolution:defhasCycle(self, head: ListNode)->bool:
count =0while head and count <=10000:
count, head = count +1, head.nextreturn count >10000