Leetcode 141 Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

LL经典题:一个指针每次前进1node,另一个指针每次前进2node,如果有环则必会到达同一node。

var hasCycle = function(head) {

    if(!head) 

        return false

    var a = head

    var b = head

    while(b.next && b.next.next){

        b = b.next.next

        a = a.next

        if(a===b)

            return true

    }

    return false

}

你可能感兴趣的:(LeetCode)