From e2ee3ea4501f75818d346b4613a4c3ab27c754ab Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 12 Jan 2022 16:25:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880142.=E7=8E=AF?= =?UTF-8?q?=E5=BD=A2=E9=93=BE=E8=A1=A8II.md=EF=BC=89=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0typescript=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 | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index dfe042b8..e8ca950d 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -294,7 +294,30 @@ var detectCycle = function(head) { }; ``` +TypeScript: + +```typescript +function detectCycle(head: ListNode | null): ListNode | null { + let slowNode: ListNode | null = head, + fastNode: ListNode | null = head; + while (fastNode !== null && fastNode.next !== null) { + slowNode = (slowNode as ListNode).next; + fastNode = fastNode.next.next; + if (slowNode === fastNode) { + slowNode = head; + while (slowNode !== fastNode) { + slowNode = (slowNode as ListNode).next; + fastNode = (fastNode as ListNode).next; + } + return slowNode; + } + } + return null; +}; +``` + Swift: + ```swift class Solution { func detectCycle(_ head: ListNode?) -> ListNode? {