package main
import (
"fmt"
)
type ListNode struct {
no int
next *ListNode
}
//插入数据
func Inster(head *ListNode, new *ListNode) {
temp := head
for {
if temp.next == nil {
break
}
temp = temp.next
}
temp.next = new
}
// 判断是否有环
//快慢指针
func fs(head *ListNode) bool {
f, s := head, head
for f != nil && f.next != nil {
s = s.next
f = f.next.next
if f == s {
return true
}
}
return false
}
//根据值判断
func has(head *ListNode) bool {
m := make(map[*ListNode]int, 0)
temp := head
for temp.next != nil && temp != nil {
m[temp] = temp.no
temp = temp.next
for _, v := range m {
if v == temp.no {
return true
}
}
}
return false
}
//根据地址判断
func has1(head *ListNode) bool {
m := make(map[*ListNode]struct{}, 0)
temp := head
for temp.next != nil && temp != nil {
m[temp] = struct{}{}
temp = temp.next
for k, _ := range m {
if k == temp {
return true
}
}
}
return false
}
func main() {
head := &ListNode{}
head1 := &ListNode{no: 1}
head2 := &ListNode{no: 2}
head3 := &ListNode{no: 3}
head4 := &ListNode{no: 4}
Inster(head, head1)
Inster(head, head2)
Inster(head, head3)
Inster(head, head4)
head4.next = head2
h := has1(head)
fmt.Println(h)
}