解题方法一
使用Set/Map记录每个节点,然后while遍历使用Set/Map.has方法判断否存在当前节点
var hasCycle = function(head) {
if (head === null) return false
const record = new Set()
while(head) {
if (record.has(head)) return true
record.add(head)
head = head.next
}
return false
}
解题方法二
使用快慢指针,慢指针每次走一步,快指针每次走两步,若快指针与慢指针相遇,说明有环,否则没环
var hasCycle = function(head) {
if (head === null) return false
let slow = head
let fast = head.next
while(fast && fast.next) {
slow = slow.next
fast = fast.next.next
if (fast == slow) return true
}
return false
}