50 lines
1.1 KiB
JavaScript
50 lines
1.1 KiB
JavaScript
/**
|
||
* https://leetcode.cn/problems/linked-list-cycle/?envType=study-plan-v2&envId=top-interview-150
|
||
* Definition for singly-linked list.
|
||
* function ListNode(val) {
|
||
* this.val = val;
|
||
* this.next = null;
|
||
* }
|
||
*/
|
||
|
||
/**
|
||
* @param {ListNode} head
|
||
* @return {boolean}
|
||
*/
|
||
const hasCycle = function (head) {
|
||
|
||
};
|
||
|
||
/*
|
||
利用set来检测在遍历的过程中是否发生了重复,如果发生了重复说明有环,如果没有表示无环
|
||
*/
|
||
|
||
function f1(head) {
|
||
const seenNodes = new Set();
|
||
|
||
let curNote = head;
|
||
|
||
while (curNote !== null) {
|
||
if (seenNodes.has(curNote)) return true; // 之前遍历出现过,直接判定有环
|
||
seenNodes.add(curNote);
|
||
curNote = curNote.next;
|
||
}
|
||
return false; // 遍历了整个链表也没有发生重复,表示无环
|
||
}
|
||
|
||
/*
|
||
通过快慢指针来判断是否有环
|
||
*/
|
||
|
||
function f2(head) {
|
||
let slow = head;
|
||
let fast = head;
|
||
|
||
while (fast !== null && fast.next !== null) {
|
||
slow = slow.next;
|
||
fast = fast.next.next;
|
||
if (slow === fast) return true; // 如果快慢指针相遇,表示有环
|
||
}
|
||
return false; // 如果快指针走到了链表末尾,表示没有环
|
||
}
|