函数:
1 ListNode* MeetingNode(ListNode* pHead) 2 { 3 if(pHead==nullptr) 4 return nullptr; 5 ListNode* quickNode=pHead; 6 ListNode* slowNode=pHead; 7 8 while(quickNode->m_pNext!=nullptr&&quickNode->m_pNext->m_pNext!=nullptr) 9 {10 quickNode=quickNode->m_pNext->m_pNext;11 slowNode=slowNode->m_pNext;12 if(quickNode==slowNode)13 break;14 }15 if(quickNode!=slowNode)16 {17 return nullptr;18 }19 return slowNode;20 }21 22 ListNode* EntryNodeOfLoop(ListNode* pHead)23 {24 ListNode* meetingNode=MeetingNode(pHead);25 if(meetingNode==nullptr)26 return nullptr;27 int nodesInLoop=1;28 ListNode* pTemp=meetingNode;29 while(pTemp->m_pNext!=meetingNode)30 {31 pTemp=pTemp->m_pNext;32 nodesInLoop++;33 }34 ListNode* quickNode=pHead;35 ListNode* slowNode=pHead;36 for(int i=0;im_pNext;38 while(slowNode!=quickNode)39 {40 quickNode=quickNode->m_pNext;41 slowNode=slowNode->m_pNext;42 }43 return slowNode;44 }
测试代码:
1 #include"List.h" 2 3 void Test(char* testName,ListNode* pHead,ListNode* expect) 4 { 5 cout<<<":"; 6 ListNode* result=EntryNodeOfLoop(pHead); 7 if(result==nullptr) 8 { 9 cout<<"No loop in the link list."<
主要要销毁所定义的指针变量和链表。如果链表中存在环,则可以一个个节点去释放。