linked-list-cycleV2.py (715B)
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 # two pointers, one fast, one slow 12 # if fast catches slow, issue 13 # if fast reaches end, success 14 15 if head is None: 16 return False 17 18 fast_ptr = head.next 19 slow_ptr = head 20 21 while fast_ptr is not None: 22 if fast_ptr == slow_ptr: 23 return True 24 25 fast_ptr = fast_ptr.next 26 27 if fast_ptr is not None: 28 fast_ptr = fast_ptr.next 29 30 slow_ptr = slow_ptr.next 31 32 return False