/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/funcdetectCycle(head*ListNode)*ListNode{slow,fast:=head,headforfast!=nil&&fast.Next!=nil{slow=slow.Nextfast=fast.Next.Nextifslow==fast{break}}iffast==nil||fast.Next==nil{returnnil}fast=headforslow!=fast{slow=slow.Nextfast=fast.Next}returnfast}
上面代码执行完检测环的 for 循环后还不能确定是否存在环,需要再次执行一次 if 判断,优化如下:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/funcdetectCycle(head*ListNode)*ListNode{slow,fast:=head,headforfast!=nil&&fast.Next!=nil{slow=slow.Nextfast=fast.Next.Nextiffast==slow{forslow!=head{head=head.Nextslow=slow.Next}returnslow}}returnnil}