给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
这个题目和判断链表是否有环的思路差不多
都是先利用快慢指针去判断链表里面是否有环,再判断哪个是环的头节点
如果pHead !== s,就让头节点和慢节点接着遍历,直到他们相等,指向的就是环的头节点
if (f == s) {
while(pHead !== s) {
pHead = pHead.next;
s = s.next;
}
return s
}
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function EntryNodeOfLoop(pHead)
{
// write code here
if (!pHead) return null
let f = pHead;
let s = pHead;
while(f && f.next) {
f = f.next.next;
s = s.next;
if (f == s) {
while(pHead !== s) {
pHead = pHead.next;
s = s.next;
}
return s
}
}
return null
}
module.exports = {
EntryNodeOfLoop : EntryNodeOfLoop
};