From 05e950c2e4aa0e1c9ddfe9476145df1f3c861c5a Mon Sep 17 00:00:00 2001 From: yi-ge Date: Sat, 9 May 2020 07:12:18 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E7=8E=AF=E5=BD=A2=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++++++ src/list/linked-list-cycle.js | 28 ++++++++++++++++++++++++++++ test/list/linked-list-cycle.test.js | 24 ++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 src/list/linked-list-cycle.js create mode 100644 test/list/linked-list-cycle.test.js diff --git a/README.md b/README.md index 2a0721b..b37bcff 100644 --- a/README.md +++ b/README.md @@ -333,9 +333,15 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - [合并两个有序链表](src/list/merge-two-sorted-lists.js) - LeetCode 21. 合并两个有序链表 https://leetcode-cn.com/problems/merge-two-sorted-lists/ + - LeetCode 面试题25. 合并两个排序的链表 https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof - LintCode 165. 合并两个排序链表 https://www.lintcode.com/problem/merge-two-sorted-lists/description - [链表排序](src/list/sort-list.js) - LeetCode 148. 排序链表 https://leetcode-cn.com/problems/sort-list/ - LintCode 98. 链表排序 https://www.lintcode.com/problem/sort-list/description + +- [环形链表](src/list/linked-list-cycle.js) + + - LeetCode 141. 环形链表 https://leetcode-cn.com/problems/linked-list-cycle/ + - LintCode 102. 带环链表 https://www.lintcode.com/problem/linked-list-cycle/description diff --git a/src/list/linked-list-cycle.js b/src/list/linked-list-cycle.js new file mode 100644 index 0000000..3459839 --- /dev/null +++ b/src/list/linked-list-cycle.js @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +export const hasCycle = function (head) { + if (!head || !head.next) return false + + // 双指针解法 + let slow = head + let fast = head.next + + while (true) { + if (!fast || !fast.next) return false + else if (fast.next === slow || fast === slow) return true + else { + fast = fast.next.next + slow = slow.next + } + } +} diff --git a/test/list/linked-list-cycle.test.js b/test/list/linked-list-cycle.test.js new file mode 100644 index 0000000..abcf7c1 --- /dev/null +++ b/test/list/linked-list-cycle.test.js @@ -0,0 +1,24 @@ +import { hasCycle } from '../../src/list/linked-list-cycle' + +function ListNode (val) { + this.val = val + this.next = null +} + +const arrToList = (arr) => { + const head = new ListNode(arr[0]) + let current = head + for (let n = 1, len = arr.length; n < len; n++) { + current.next = new ListNode(arr[n]) + current = current.next + } + + return head +} + +test('环形链表', () => { + const list = arrToList([1, 2, 3]) + list.next.next.next = list + expect(hasCycle(list)).toBe(true) + expect(hasCycle(arrToList([1, 2, 3]))).toBe(false) +})