面試題23:連結串列中環的入口節點
阿新 • • 發佈:2020-07-25
考察連結串列的操作,找到單向連結串列中環的入口節點
C++版
#include <iostream> #include <algorithm> using namespace std; // 定義連結串列 struct ListNode{ int val; struct ListNode* next; ListNode(int val):val(val),next(nullptr){} }; // 在連結串列存在環的前提下找到一快一慢兩個指標相遇的節點 ListNode* MeetingNode(ListNode* pHead){ if(pHead == nullptr) return nullptr; // 定義走的慢節點 ListNode* pSlow = pHead->next; if(pSlow == nullptr) return nullptr; // 定義走的快的節點 ListNode* pFast = pSlow->next; while(pFast != nullptr && pSlow != nullptr){ if(pFast == pSlow) return pFast; // 慢節點走一步 pSlow = pSlow->next; pFast = pFast->next; // 快節點走兩步 if(pFast->next != 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){ pNode1 = pNode1->next; nodesInLoop++; } // 先移動pNode1,次數為環中節點的數目 pNode1 = pHead; for(int i = 0; i < nodesInLoop; i++){ pNode1 = pNode1->next; } ListNode* pNode2 = pHead; while(pNode1 != pNode2){ pNode1 = pNode1->next; pNode2 = pNode2->next; } return pNode1; } int main() { char *p = "hello"; // p[0] = 'H'; cout<<p<<endl; return 0; }