Skip to content
Home » X Algorithm – 250 LeetCode Coding Challenge Questions » Page 4

X Algorithm – 250 LeetCode Coding Challenge Questions

Linked List Cycle Detection

const hasCycle = head => {
    let p1 = head
    let p2 = head
    
    while (p2 && p2.next && p2.next.next) { // p2 not stop, it means not reach the end, other wise, no cycle
        p1 = p1.next
        p2 = p2.next.next
// each interaction, fast and slow pointers' distance will increase by 1
        
        if (p1 === p2) {
            return true
        }
    }
    
    return false
}
// from https://leetcode.com/problems/linked-list-cycle/discuss/375999/Slow-%2B-Fast-Runner-in-Javascript

Leave a Reply

Pages: 1 2 3 4