查看: 76|回复: 0

LeetCode:141.环形链表

[复制链接]

1

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2012-7-3
发表于 2025-1-10 21:32:00 | 显示全部楼层 |阅读模式
// 双指针 快+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);
        p = p.next;
    }
    return head.next;
}



来源:https://www.cnblogs.com/KooTeam/p/18664757
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部