/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funchasCycle(head *ListNode)bool { if head == nil || head.Next == nil { returnfalse } slow := head //慢指针 fast := head.Next //快指针 for fast != nil && fast.Next != nil { fast = fast.Next.Next slow = slow.Next if slow == fast { //一块一慢,如果两个指针指向同一个值,说明链表有环 returntrue } }