问题:
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
/*function ListNode(x){ this.val = x; this.next = null; }*/ function EntryNodeOfLoop(pHead) { // write code here let mNode = meetNode(pHead);//获得两个指针在环中相遇的节点,若为null,则该链表中没有环 if(mNode == null){ return null; } //如何得到环中节点的个数 let number = 1; let p = mNode; while(p.next!=mNode){ number++; p = p.next; } //再利用两个指针 一个先移动number步,然后两个指针再一起移动,直到两者相遇 let p1 = pHead; for(let i=0;i<number;i++){ p1 = p1.next; } let p2 = pHead; while(p1!=p2){ p1 = p1.next; p2 = p2.next; } return p1; } function meetNode(pHead){ if(pHead==null){ return null; } let pSlow = pHead.next; if(pSlow==null){ return null;//链表中只有一个节点 且没有环 } let pFast = pSlow.next; while(pFast!=null&&pSlow!=null){ if(pFast==pSlow){ //如果两个指针相遇 return pFast; } pSlow = pSlow.next; pFast = pFast.next; if(pFast!=null){ pFast = pFast.next; } } //一直到链表尾两个指针都没有相遇 return null; }