# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: # @param head, a ListNode # @return a boolean defhasCycle(self, head): slow=head ifnot slow ornot slow.next: returnFalse fast=slow.next.next while fast and fast.next: if slow==fast: returnTrue slow=slow.next fast=fast.next.next returnFalse