链表是否有环-快慢指针
2019-12-13 本文已影响0人
斯嘎啦
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil || head.Next == nil{
return false
}
slow, fast := head, head
for slow != nil && fast != nil && fast.Next !=nil{
slow = slow.Next
fast = fast.Next.Next
if fast == slow{
return true
}
}
return false
}