package main
import "fmt"
type ListNode struct {
Data interface{}
Next *ListNode
}
//链表中是否存在环
func HasCycle(head *ListNode) bool {
if head == nil {
return false
}
fast, slow := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
return true
}
}
return false
}
//求链表环的长度
func CycleLen(head *ListNode)int{
var flag bool
var length int
if head == nil {
return 0
}
fast, slow := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
flag=true
break
}
}
if flag ==false{
return 0
}
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
length++
if slow == fast {
break
}
}
return length
}
//求环的节点入口
//有定理:碰撞点p到连接点的距离=头指针到连接点的距离,因此,分别从碰撞点、头指针开始走,相遇的那//个点就是连接点。
func FindLoopEntry(head *ListNode)*ListNode{
fast, slow := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
break
}
}
if fast == nil || fast.next == nil{
return nil
}
slow = head
for slow != fast{
slow = slow.next
fast = fast.next
}
return slow
}
func main() {
var node1 = new(ListNode)
var node2 = new(ListNode)
var node3 = new(ListNode)
var node4 = new(ListNode)
var node5 = new(ListNode)
node1.Data = 1
node2.Data = 2
node3.Data = 3
node4.Data = 4
node5.Data = 5
node1.Next = node2
node2.Next = node3
node3.Next = node4
node4.Next = node2
//node4.Next = node5
hasCycle := HasCycle(node1)
fmt.Printf("This list has cycle? Yes or No: %v\n", hasCycle)
}
2.判断链表是否有环、环的长度、环的入口
最新推荐文章于 2024-08-16 10:42:04 发布