linked-list-cycle.py (528B)
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 8 class Solution: 9 def hasCycle(self, head: Optional[ListNode]) -> bool: 10 11 if head is None: 12 return False 13 14 head.val = None 15 current = head.next 16 17 while current is not None: 18 if current.val is None: 19 return True 20 else: 21 current.val = None 22 current = current.next 23 24 return False