add: 环形链表
This commit is contained in:
28
src/list/linked-list-cycle.js
Normal file
28
src/list/linked-list-cycle.js
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user