题目
代码实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
fast, slow := head, head
for slow != nil && fast != nil && fast.Next != nil {
fast = fast.Next.Next
slow = slow.Next
if fast == slow {
return true
}
}
return false
}
/*
func hasCycle(head *ListNode) bool {
fast, slow := head, head
for {
if fast == nil || fast.Next == nil {
return false // 无环
}
fast = fast.Next.Next
slow = slow.Next
if fast == slow {
return true
}
}
}
*/
解题思路:使用快慢指针(slow一次走一步,fast一次走两步)。如果不含有环,fast最终会遇到 nil,说明链表不含环;如果含有环,fast最终会超slow一圈,和slow相遇,说明链表含有环。