Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013

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

3+1官网

我也要出题

Activity

hzy-caiji

hzy-caiji commented on May 15, 2021

@hzy-caiji

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

seafronthu

seafronthu commented on Jun 11, 2024

@seafronthu
// 使用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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@seafronthu@hzy-caiji

        Issue actions

          [js] 第649天 如何判断链表是否有环? · Issue #3478 · haizlin/fe-interview