题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:参考书籍《剑指offer》
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* MeetingNode(ListNode* pHead){
if(pHead == nullptr)
return nullptr;
ListNode* pSlow = pHead->next;
if(pSlow == nullptr)
return nullptr;
ListNode* pFast = pSlow->next;
while(pSlow != nullptr && pFast != nullptr){
if(pSlow == pFast)
return pSlow;
pSlow = pSlow->next;
pFast = pFast->next;
if(pFast != nullptr)
pFast = pFast->next;
}
return nullptr;
}
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
//判断是否有闭环,并且找到闭环中的一个相遇节点
ListNode* meetingNode = MeetingNode(pHead);
if(meetingNode == nullptr)
return nullptr;
//获得闭环的节点数
int nodesInLoop = 1;
ListNode* pNode1 = meetingNode;
while(pNode1->next != meetingNode){
nodesInLoop++;
pNode1 = pNode1->next;
}
//获得闭环的入口节点
pNode1 = pHead;
ListNode* pNode2 = pHead;
//节点1先前进nodesInLoop步
while(nodesInLoop--){
pNode1 = pNode1->next;
}
while(pNode1 != pNode2){
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
return pNode1;
}
};