快慢指针,如果相遇了说明有环,遍历完没相遇就没环。注意while循环的条件
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = head
slow = head
while fast and fast.next: #同时判断的原因是fast可能为空,fast.next也可能为空
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False