注意的点:
1、注意里面的判断条件,虽然代码少但是其实逻辑很多。
解法:快慢指针
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 快慢指针
slow, fast = head, head
if not head: return None
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
if slow == fast: break # 得放在后面
if not fast.next or not fast.next.next:
return None
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return fast