判断给定的链表中是否有环。如果有环则返回true,否则返回false。
使用的是快慢指针
如果链表里面有环,那么总有一个时刻快指针和慢指针会相遇
- 最开始的时候 fast slow 都指向头节点
- 开始遍历,fast走两步,slow走一步 一直到fast != null && fast.next != null
- 如果在两个指针走的过程中,存在fast == slow
- 存在环
- 否则返回false
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
function hasCycle( head ) {
if(!head) {
return false
}
let slow = head;
let fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow === fast) return true
}
return false
// write code here
}
module.exports = {
hasCycle : hasCycle
};

被折叠的 条评论
为什么被折叠?



