思路
采用雙指針法,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