141. Linked List Cycle
在 Q202 里用过的龟兔赛跑快慢指针
,相遇即证明有环。
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head: return False
slow = head
fast = head.next
while fast != slow:
if not fast or not fast.next: return False
else:
fast = fast.next.next
slow = slow.next
return True
Last updated
Was this helpful?