题目链接:https://leetcode.cn/problems/linked-list-cycle-ii/
难度:中等

描述:
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 _null_

题解

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def detectCycle(self, head: ListNode) -> ListNode:
  8. slow = fast = head
  9. while fast and fast.next:
  10. slow = slow.next
  11. fast = fast.next.next
  12. if slow == fast:
  13. fast = head
  14. while slow != fast:
  15. fast = fast.next
  16. slow = slow.next
  17. return fast
  18. return None