add: 环形链表

This commit is contained in:
yi-ge 2020-05-09 07:12:18 +08:00
parent c027a13f6e
commit 05e950c2e4
3 changed files with 58 additions and 0 deletions

View File

@ -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

View File

@ -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
}
}
}

View File

@ -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)
})