142. 环形链表 II
题目描述
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
原题请参考链接https://leetcode-cn.com/problems/linked-list-cycle-ii/
题解
方法一 【双指针(快慢指针)、数学】
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow = head
fast = head
# 最外层while判断是否有环
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 有环的情况
if slow == fast:
index0 = head
index1 = fast
# 搜索环入口
while index0 != index1:
index0 = index0.next
index1 = index1.next
return index0
return None
python

浙公网安备 33010602011771号