142. 环状链表 II

题目描述

思路
「141. 环形链表」本质上是这道题目的简化,因此我们就跳过 Hot 100 当中的这道题目,直接来将「142. 环形链表 II」。
想要找到环形链表的入口,我们需要记住一个结论,那就是当我们首先通过快慢指针找到环形链表当中的相交点时,令slow, fast := head, intersection(intersection是相交点),然后同时令它们不断地后移一个节点,最终它们相遇的位置,就是环的入口。
基于以上思路,我们来写代码解决这道题。
Golang 题解
go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(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 {
break
}
}
fast = head
for slow != fast && slow != nil {
slow, fast = slow.Next, fast.Next
}
return slow
}