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: 链表中环的入口节点 (链表中环的入口节点)
// @Author: 15816537946@163.com
// @Date: 2022-03-26 17:51:13
// @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 slow == fast {
for slow != head {
slow, head = slow.Next, head.Next
}
return head
}
}
return nil
}
|