From 0a7682998d60cf02caab772ba74955baf1ad806e Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Wed, 19 May 2021 11:22:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0142.=E7=8E=AF=E5=BD=A2?= =?UTF-8?q?=E9=93=BE=E8=A1=A8IIjavascript=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 | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index b3a53c07..71f5cc4c 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -258,6 +258,50 @@ Go: } ``` +javaScript + +```js +// 两种循环实现方式 +/** + * @param {ListNode} head + * @return {ListNode} + */ +// 先判断是否是环形链表 +var detectCycle = function(head) { + if(!head || !head.next) return null; + let slow =head.next, fast = head.next.next; + while(fast && fast.next && fast!== slow) { + slow = slow.next; + fast = fast.next.next; + } + if(!fast || !fast.next ) return null; + slow = head; + while (fast !== slow) { + slow = slow.next; + fast = fast.next; + } + return slow; +}; + +var detectCycle = function(head) { + if(!head || !head.next) return null; + let slow =head.next, fast = head.next.next; + while(fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + if(fast == slow) { + slow = head; + while (fast !== slow) { + slow = slow.next; + fast = fast.next; + } + return slow; + } + } + return null; +}; +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)