classSolution: defhasCycle(self, head: ListNode) -> bool: slow = fast = head ifnot head: returnFalse while fast and fast.next: fast = fast.next.next slow = slow.next if slow == fast: returnTrue returnFalse
还可以用来判断环的入口位置
环形链表II(142)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defdetectCycle(self, head: ListNode) -> ListNode: fast = slow = head ifnot head: returnNone while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: left, right = head, fast while left != right: left = left.next right = right.next return left returnNone
classSolution: defdetectCycle(self, head: ListNode) -> ListNode: fast = slow = head ifnot head: returnNone while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: left, right = head, slow if left == right: return left whileTrue: left = left.next right = right.next if left == right: return left returnNone
classSolution: defmiddleNode(self, head: ListNode) -> ListNode: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow