Shu-How Zの小窝

Loading...

LeetCode:141.环形链表

// 双指针 快+1=慢 true
class ListNode {
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}
var hasCycle = function(head) {
    let fast=head
    let slow=head
    while(fast&&slow&&fast.next){
        if(fast.next===slow){
            return true
        }else{
            fast=fast.next.next
            slow=slow.next
        }
    }
    return false
};

let arr = [1,2]
let head=buildLinkedList(arr)
head.next = head;
console.log(hasCycle(head));

function buildLinkedList(arr) {
    let head = new ListNode(0);
    let p = head;
    for (let i = 0; i < arr.length; i++) {
        p.next = new ListNode(arr[i]);
        p = p.next;
    }
    return head.next;
}

posted @ 2025-01-10 21:32  KooTeam  阅读(10)  评论(0)    收藏  举报