add: 环形链表

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

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