题解 | #链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* pSlow=pHead;
ListNode* pFast=pSlow;
//快指针一下走两步,慢指针走一步,若相遇则退出循环
while(pFast&&pFast->next){
pFast=pFast->next->next;
pSlow=pSlow->next;
if(pFast==pSlow){
break;
}
}
if(pFast==nullptr||pFast->next==nullptr)
return nullptr;
//快指针回到头结点,慢指针在相遇点,前行
pFast=pHead;
while(pFast!=pSlow){
pFast=pFast->next;
pSlow=pSlow->next;
}
return pSlow;
}
};
快慢指针法