对于一个给定的链表,返回环的入口节点,如果没有环,返回null
拓展:
你能给出不利用额外空间的解法么?
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return ListNode类
*/
function detectCycle( head ) {
// write code here
if(head==null||head.next==null){return null}
var slow = head
var fast = head
while(fast&&fast.next){
slow = slow.next
fast = fast.next.next
if(fast==slow){
let p = head
while(p!==slow){
p = p.next
slow = slow.next
}
return p
}
}
return null
}
module.exports = {
detectCycle : detectCycle
};