問題:一個(gè)單向鏈表,怎樣怎么檢測(cè)是否有環(huán),環(huán)的初始節(jié)點(diǎn)是什么?
package main
import (
"fmt"
)
type ListNode struct {
value int
next *ListNode
}
func NewListNode(i int) *ListNode {
val := new(ListNode)
val.value = i
return val
}
func main() {
a1 := NewListNode(1)
a2 := NewListNode(2)
a3 := NewListNode(3)
a4 := NewListNode(4)
a5 := NewListNode(5)
// 1→2→3→4→5
// ↑????
a1.next = a2
a2.next = a3
a3.next = a4
a4.next = a5
a5.next = a3
head := DetectCycle(a1)
fmt.Println(head.value)
}
func DetectCycle(head *ListNode) *ListNode {
fast := head
slow := head
for {
if fast.next == nil || slow.next == nil {
break
}
fast = fast.next.next
slow = slow.next
if fast == slow {
// 找到快慢指針相遇點(diǎn)
break
}
}
if fast == nil || slow == nil {
return nil
}
// 找到快慢指針相遇點(diǎn)后,快慢指針一樣的速度移動(dòng),找到環(huán)的起點(diǎn)
slow = head
for {
if fast == slow {
break
}
fast = fast.next
slow = slow.next
}
return slow
}