/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funchasCycle(head *ListNode)bool { hashMap := make(map[*ListNode]bool) p := head // 遍历指针
for p != nil { if _, ok := hashMap[p]; !ok { // 当前节点之前没有遍历过,记录在哈希表中 hashMap[p] = true } else { // 当前遍历的节点之前已经遍历过,说明有环 returntrue } p = p.Next } // 每一个节点都只被遍历了一次,没有环 returnfalse }
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ funchasCycle(head *ListNode)bool { if head == nil || head.Next == nil { returnfalse }
// 定义快慢指针 slow, fast := head, head.Next
for slow != fast { if fast == nil || fast.Next == nil { returnfalse } slow = slow.Next // 慢指针走一步 fast = fast.Next.Next // 快指针走两步 }