题目:如果一个链表中包含环,如何找出环的入口节点。
type Node struct {
val int
next *Node
}
func hasCir(head *Node) (*Node, bool) {
if head == nil || head.next == nil || head.next.next == nil {
return nil, false
}
front, tail := head.next, head
for front != nil && front.next != nil && front != tail {
front = front.next.next
tail = tail.next
}
if front == tail {
return front, true
}
return nil, false
}
func NodeNumCir(head *Node) int {
p, hCir := hasCir(head)
if !hCir {
return 0
}
pm := p.next
count := 1
for p != pm {
count++
pm = pm.next
}
return count
}
func CirFirstNode(head *Node) int {
if head == nil {
return 0
}
nodeCount := NodeNumCir(head)
if nodeCount < 1 {
return 0
}
front, tail := head, head
for i := 0; i < nodeCount; i++ {
front = front.next
}
for front != tail {
front = front.next
tail = tail.next
}
return front.val
}