思路:
判断是否有环:定义两个指针 fast 和 slow 都指向 head,fast 每次前进两个节点,slow 每次前进一个节点,这样两个指针移动的差值是1,所以如果有环,fast 和 slow 一定会相遇。
确定环的入口:指针 index1 指向 head,指针 index2 指向 fast,同时前进,相遇的节点就是环的入口。
class Solution(object):
def detectCycle(self, head):
fast = slow = head
s=f=0
cycle = 0
if head==None:return None
while fast.next and fast.next.next and slow.next:
fast=fast.next.next
f+=2
slow=slow.next
s+=1
if slow==fast:
cycle=1
break
if cycle==0:
return None
index1=head
index2=fast
count=0
while index1!=index2:
index1=index1.next
index2=index2.next
count+=1
return index1
题解:
方法一:快慢指针法
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# If there is a cycle, the slow and fast pointers will eventually meet
if slow == fast:
# Move one of the pointers back to the start of the list
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
# If there is no cycle, return None
return None
方法二:集合法:
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
visited = set()
while head:
if head in visited:
return head
visited.add(head)
head = head.next
return None
知识点
python 集合
集合(set)是一个无序的不重复元素序列,可以使用大括号 { } 创建集合,元素之间用逗号分隔, 或者也可以使用 set() 函数创建集合。创建一个空集合必须用 set()
添加元素:s.add( x )
计算集合中元素个数:len( s )
判断元素是否在集合中:x in s