脑残网友真多 發表於 2025-1-10 21:32:00

LeetCode:141.环形链表

<pre><code class="language-js">// 双指针 快+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&amp;&amp;slow&amp;&amp;fast.next){
      if(fast.next===slow){
            return true
      }else{
            fast=fast.next.next
            slow=slow.next
      }
    }
    return false
};

let arr =
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 &lt; arr.length; i++) {
      p.next = new ListNode(arr);
      p = p.next;
    }
    return head.next;
}

</code></pre><br><br>
来源:https://www.cnblogs.com/KooTeam/p/18664757
頁: [1]
查看完整版本: LeetCode:141.环形链表