面试题23:链表中环的入口结点
题目:一个链表中包含环,如何找出环的入口结点?例如,在下图的链表中,环的入口结点是结点3。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
struct ListNode{
int value;
ListNode* next;
};
ListNode* MeetingNode(ListNode* pHead){ // 找到一快一满两个指针相遇的节点
if(pHead==NULL) return NULL;
ListNode* pSlow=pHead->next;
if(pSlow==NULL) return NULL;
ListNode* 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;
}
ListNode* EntryNodeOfLoop(ListNode* pHead){
ListNode* meetingNode=MeetingNode(pHead);
if(meetingNode==NULL) return NULL;
// 得到环中节点的数目
int nodesInLoop=1;
ListNode* pNode1=meetingNode;
while(pNode1->next!=meetingNode){
pNode1=pNode1->next;
++nodesInLoop;
}
// 先移动 pNode1, 次数为环中节点的数目
pNode1=pHead;
for(int i=0;i<nodesInLoop;i++){
pNode1=pNode1->next;
}
// 再一起移动pNode1和pNode2
ListNode* pNode2=pHead;
while(pNode1!=pNode2){
pNode1=pNode1->next;
pNode2=pNode2->next;
}
return pNode1;
}
int main() {
return 0;
}