思路
采用双指针法,slow指针每次走一步,fast指针每次走两步,如果相遇的情况下,slow指针回到开始的位置,此时快慢指针各走一步,当相遇的时候也就是说明链表中有环。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:def hasCycle(self, head: Optional[ListNode]) -> bool:if not head:return None #空节点的时候slow=headfast=headwhile fast.next!=None and fast.next.next!=None:slow=slow.nextfast=fast.next.nextif slow==fast:slow=headwhile slow!=fast:slow=slow.nextfast=fast.nextreturn slowreturn None