【剑指offer】链表中环的入口结点

题目链接:链表中环的入口结点

 

题意:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

 

题解:我们设置两个指针,一个走的快,一个走得慢。如果有环,快慢指针一定会相遇。

并且,两个指针一个从头走,一个走相遇点走,最后一定会在环入口相遇。

所以我们先找到环节点的个数,再让快指针先走c环节点个,就能找到环入口节点。

 

代码:

 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     ListNode* EntryNodeOfLoop(ListNode* pHead){
13         //快指针和慢指针
14         ListNode* fast = pHead,*slow=pHead->next;
15         while(fast!=slow && fast!=NULL && slow != NULL){
16             slow = slow->next;
17             fast = fast->next;
18             if(fast!=NULL)    fast = fast->next;
19         }
20         //链表环节点个数
21         int cnt = 1;
22         ListNode *node = fast->next;
23         if(fast == slow && fast!=NULL){
24             while(node != fast){
25                 node = node->next;
26                 cnt++;
27             }
28         }
29         else    return NULL;
30        
31         fast = pHead;slow = pHead;
32         //fast先走cnt
33         for(int i = 0; i < cnt; i++)    fast = fast->next;
34         //找到入口
35         while(fast != slow){
36             fast = fast->next;
37             slow = slow->next;
38         }
39         return fast;
40     }
41 };

猜你喜欢

转载自www.cnblogs.com/Asumi/p/12423379.html