add: 环形链表
This commit is contained in:
1 parent
c027a13f6e
commit
05e950c2e4
3 files changed
+58
No files matched your search
@@ -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