fe-interview
fe-interview copied to clipboard
[js] 第649天 如何判断链表是否有环?
var hasCycle = function(head) { const res = []; let f =false; while (head) { if (res.includes(head)) { f = true; break } res.push(head); head = head.next; } return f; };
// 使用Map
function hasCycle(head: ListNode | null): boolean {
const listNodeMap = new Map()
if (!head) {
return false
}
let listNode = head
listNodeMap.set(listNode, listNode.val)
while(listNode) {
const nextListNode = listNode.next
if (!nextListNode) {
return false
}
if (listNodeMap.has(nextListNode)) {
return true
}
listNodeMap.set(nextListNode, nextListNode.val)
listNode = nextListNode
}
};
// 使用快慢指针(龟兔赛跑)
function hasCycle(head: ListNode | null): boolean {
if (!head || !head.next) {
return false
}
let slow = head
let fast = head.next
while(slow !== fast) {
if (!fast || !fast.next) {
return false
}
slow = slow.next
fast = fast.next.next
}
return true
};