[swift 外部干涉法 extension]

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */
// ListNode 要实现以下两个,如何外部干涉
// Equatable
// Hashable
extension ListNode: Equatable {
    public static func == (l: ListNode, r: ListNode) -> Bool {
        return l === r
    }
}

extension ListNode: Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
}




// 快慢指针,快指针 追上慢指针
class Solution {
    func hasCycle(_ head: ListNode?) -> Bool {
        var slow: ListNode? = head 
        var fast: ListNode? = head 

        while fast?.next != nil {
            slow = slow?.next
            fast = fast?.next?.next
            if fast == slow {
                return true
            }
        }
        return false
    }
}
posted @ 2025-10-04 17:18  十三山入秋  阅读(8)  评论(0)    收藏  举报