我们可以.用两个指针:one slow and one fast来解决这个问题,slow走一步,fast走两步,slow与fast相遇的地方是slow第一次到达,fast第二次到达的地方
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow=fast=head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
if id(slow)==id(fast):
return True
return False