检测链表中的环 swift

func hasCycle(_ head: ListNode?) -> Bool {
    var slow = head, fast = head
    while fast != nil && fast?.next != nil {
        slow = slow?.next
        fast = fast?.next?.next
        if slow === fast { return true }
    }
    return false
}

 

posted @ 2025-02-08 15:26  黄增松  阅读(12)  评论(0)    收藏  举报