diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 91e14e27..4a3f36b0 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -296,6 +296,39 @@ var detectCycle = function(head) { }; ``` +Swift: +```swift +class Solution { + func detectCycle(_ head: ListNode?) -> ListNode? { + var slow: ListNode? = head + var fast: ListNode? = head + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + if slow == fast { + // 环内相遇 + var list1: ListNode? = slow + var list2: ListNode? = head + while list1 != list2 { + list1 = list1?.next + list2 = list2?.next + } + return list2 + } + } + return nil + } +} +extension ListNode: Equatable { + public func hash(into hasher: inout Hasher) { + hasher.combine(val) + hasher.combine(ObjectIdentifier(self)) + } + public static func == (lhs: ListNode, rhs: ListNode) -> Bool { + return lhs === rhs + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)