函数:
ListNode* MeetingNode(ListNode* pHead)
{
if(pHead==nullptr)
return nullptr;
ListNode* quickNode=pHead;
ListNode* slowNode=pHead; while(quickNode->m_pNext!=nullptr&&quickNode->m_pNext->m_pNext!=nullptr)
{
quickNode=quickNode->m_pNext->m_pNext;
slowNode=slowNode->m_pNext;
if(quickNode==slowNode)
break;
}
if(quickNode!=slowNode)
{
return nullptr;
}
return slowNode;
} ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* meetingNode=MeetingNode(pHead);
if(meetingNode==nullptr)
return nullptr;
int nodesInLoop=;
ListNode* pTemp=meetingNode;
while(pTemp->m_pNext!=meetingNode)
{
pTemp=pTemp->m_pNext;
nodesInLoop++;
}
ListNode* quickNode=pHead;
ListNode* slowNode=pHead;
for(int i=;i<nodesInLoop;i++)
quickNode=quickNode->m_pNext;
while(slowNode!=quickNode)
{
quickNode=quickNode->m_pNext;
slowNode=slowNode->m_pNext;
}
return slowNode;
}
测试代码:
#include"List.h" void Test(char* testName,ListNode* pHead,ListNode* expect)
{
cout<<testName<<":";
ListNode* result=EntryNodeOfLoop(pHead);
if(result==nullptr)
{
cout<<"No loop in the link list."<<endl;
}
else if(result==expect)
{
cout<<"Passed."<<endl;
}
else
cout<<"Failed."<<endl;
} void Test1_7()
{
ListNode* pNode1=CreateListNode();
ConnectListNodes(pNode1,pNode1);
Test("test1",pNode1,pNode1);
ListNode* pNode2=CreateListNode();
ListNode* pNode3=CreateListNode();
ListNode* pNode4=CreateListNode();
ListNode* pNode5=CreateListNode();
ListNode* pNode6=CreateListNode(); ConnectListNodes(pNode1,pNode2);
ConnectListNodes(pNode2,pNode3);
ConnectListNodes(pNode3,pNode4);
ConnectListNodes(pNode4,pNode5);
ConnectListNodes(pNode5,pNode6);
ConnectListNodes(pNode6,pNode3);
Test("test2",pNode1,pNode3);
ConnectListNodes(pNode6,pNode6);
Test("test3",pNode1,pNode6);
Test("test4",nullptr,nullptr);
ConnectListNodes(pNode6,nullptr);
Test("test5",pNode1,nullptr);
DestroyList(pNode1);//注意销毁所定义的指针和链表
} int main()
{
Test1_7();
return ;
}
主要要销毁所定义的指针变量和链表。如果链表中存在环,则可以一个个节点去释放。