链表是否有环-快慢指针

/**
 * 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
}

你可能感兴趣的:(链表是否有环-快慢指针)