From 21e4c0e93e11f7a2614a4dfbe4af8c201a3f03b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Tue, 24 Aug 2021 13:28:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20142.=E7=8E=AF=E5=BD=A2?= =?UTF-8?q?=E9=93=BE=E8=A1=A8II=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0142.环形链表II.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) 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)