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

题目链表中环的入口结点

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {

    }
};

解题代码:

 1 class Solution {
 2 public:
 3     ListNode* EntryNodeOfLoop(ListNode* pHead) {
 4         if(pHead == nullptr)
 5             return nullptr;
 6         // 判断链表是否有环
 7         // 若含有环,则返回环中某个节点的地址
 8         // 否则,返回nullptr
 9         ListNode* temp = mergeNode(pHead);
10         if(temp == nullptr)
11             return nullptr;
12         // 求解环中含有几个节点
13         ListNode* start = temp->next;
14         int count = 1;
15         while(start != temp){
16             start = start->next;
17             count++;
18         }
19         //寻找环的入口节点
20         ListNode* p1 = pHead;
21         ListNode* p2 = pHead;
22         // 先移动p1
23         for(int i = 0; i < count; i++)
24             p1 = p1->next;
25         // p1, p2 一起移动
26         while(p1 != p2){
27             p1 = p1->next;
28             p2 = p2->next;
29         }
30         return p1;
31     }
32 private:
33     ListNode* mergeNode(ListNode* pHead){
34         ListNode* slow = pHead->next;
35         if(slow == nullptr)
36             return nullptr;
37         ListNode* fast = slow->next;
38         while (fast != nullptr) {
39             if(slow == fast)
40                 return fast;
41 
42             slow=slow->next;
43             fast=fast->next;
44 
45             if(fast != nullptr && fast != slow)
46                 fast=fast->next;
47         }
48         return nullptr;
49     }
50 };
原文地址:https://www.cnblogs.com/iwangzhengchao/p/9867388.html