题目描述
一个链表中包含环,请找出该链表的环的入口结点。
解题思路:先通过快慢指针,找到环中结点,以确定环中结点个数,然后两个指针,一个先走环中结点个数步,然后两个指针一起走,直到相遇得为入口节点
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 //通过快慢指针找到在环中的相遇点 13 ListNode* MeetingNode(ListNode *pHead) 14 { 15 //找到在环中的结点--快慢指针 16 if(pHead == NULL) 17 return NULL; 18 ListNode *slow = pHead; 19 ListNode *fast = pHead; 20 while(fast != NULL && fast->next != NULL) 21 { 22 slow = slow->next; 23 fast = fast->next->next; 24 if(fast == slow)//注意此处先移动,再判断 25 return fast; 26 } 27 return NULL; 28 } 29 ListNode* EntryNodeOfLoop(ListNode* pHead) 30 { 31 ListNode *meetNode = MeetingNode(pHead); 32 if(meetNode == NULL) 33 return NULL; 34 int nodesInLoop = 1; 35 ListNode *pNode1 = meetNode; 36 while(pNode1->next != meetNode) 37 { 38 pNode1 = pNode1->next; 39 nodesInLoop++; 40 } 41 pNode1 = pHead; 42 for(int i=0;i<nodesInLoop;i++) 43 { 44 pNode1 = pNode1->next; 45 } 46 ListNode *pNode2 = pHead; 47 while(pNode1 != pNode2) 48 { 49 pNode1 = pNode1->next; 50 pNode2 = pNode2->next; 51 } 52 return pNode1; 53 } 54 };
时间: 2024-10-04 01:34:15