funchasCycle(head *ListNode)bool{// 边界if head ==nil|| head.Next ==nil{returnfalse}
slow, fast := head, head
for fast !=nil{
slow = slow.Next
fast = fast.Next
if fast !=nil{
fast = fast.Next
}if slow == fast {returntrue}}returnfalse}
funcdetectCycle(head *ListNode)*ListNode {if head ==nil|| head.Next ==nil{returnnil}
inLoop :=nodeInLoop(head)if inLoop ==nil{returnnil}
cnt :=cycleNodeCount(inLoop)// 前后指针
front := head
for i :=0; i < cnt; i++{
front = front.Next
}
back := head
for back != front {
back = back.Next
front = front.Next
}return back
}funccycleNodeCount(node *ListNode)int{
count :=1
cur := node.Next
for cur != node {
cur = cur.Next
count++}return count
}funcnodeInLoop(head *ListNode)*ListNode {
slow, fast := head, head
for fast !=nil{
slow = slow.Next
fast = fast.Next
if fast !=nil{
fast = fast.Next
}if slow == fast {return slow
}}returnnil}
funcdetectCycle(head *ListNode)*ListNode {if head ==nil|| head.Next ==nil{returnnil}
inLoop :=findNodeInLoop(head)if inLoop ==nil{returnnil}
node := head
for node != inLoop {
node = node.Next
inLoop = inLoop.Next
}return node
}funcfindNodeInLoop(head *ListNode)*ListNode {
slow, fast := head, head
for fast !=nil{
slow = slow.Next
fast = fast.Next
if fast !=nil{
fast = fast.Next
}if slow == fast {return slow
}}returnnil}