LeetCode – 141. Linked List Cycle

題目連結: https://leetcode.com/problems/linked-list-cycle/

    func hasCycle(_ head: ListNode?) -> Bool {
        guard let head = head else { return false }
        var ptr1: ListNode? = head
        var ptr2: ListNode? = head
        while ptr1 != nil && ptr2 != nil {
            ptr1 = ptr1?.next
            ptr2 = ptr2?.next?.next
            if ptr1 != nil && ptr2 != nil && ptr1 === ptr2 {
                return true
            }
        }
        return false
    }