用链表是否有环的第三种解题方式来做,传送门,思路也非常简单,不断地打断链表,如果存在环,那判断条件成理的地方肯定就是环的入口。
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
if(pHead == NULL)
return NULL;
if(pHead->next == pHead)
return pHead;
ListNode* tmp = pHead->next;
pHead->next = pHead;
return EntryNodeOfLoop(tmp);
}
};

京公网安备 11010502036488号