/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
listMap := map[*ListNode]struct{}{}
for head != nil {
if _, ok := listMap[head]; ok {
return true
}
listMap[head] = struct{}{}
head = head.Next
}
return false
}
func hasCycle2(head *ListNode) bool {
if head == nil || head.Next == nil {
return false
}
slow := head
fast := head.Next
// 快慢指针相遇,说明有环
for slow != fast {
if fast == nil || fast.Next == nil {
return false
}
slow = slow.Next
fast = fast.Next.Next // 快指针走两步
}
return true
}
标签:head,return,nil,141,环形,fast,Next,链表,ListNode
From: https://www.cnblogs.com/gdut17code/p/18237358