1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// @Title: 环形链表 II (Linked List Cycle II)
// @Author: 15816537946@163.com
// @Date: 2022-03-26 18:07:22
// @Runtime: 4 ms
// @Memory: 3.5 MB
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */


func detectCycle(head *ListNode) *ListNode {
	slow, fast := head, head
	for fast != nil && fast.Next != nil {
		slow, fast = slow.Next, fast.Next.Next
		if fast == slow {
			for head != slow {
				head, slow = head.Next, slow.Next
			}
			return head
		}
	}
	return nil
}