fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[js] 第649天 如何判断链表是否有环?

Open haizhilin2013 opened this issue 4 years ago • 2 comments

第649天 如何判断链表是否有环?

3+1官网

我也要出题

haizhilin2013 avatar Jan 23 '21 20:01 haizhilin2013

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

hzy-caiji avatar May 15 '21 09:05 hzy-caiji

// 使用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
};

seafronthu avatar Jun 11 '24 07:06 seafronthu