/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* ptr = pHead;
ListNode* fast = pHead; //定义两个指针记录头结点的位置
int count = 10;
while (count > 0 && fast) { //让指针走十次看链表有没有环
fast = fast->next;
if (fast == nullptr) {
return nullptr;
}
count--;
}
//链表有环的话,每遍历一个节点,就把前一个结点断开,直到pHead->next为空,此时pHead就是入口节点
while (pHead->next) {
pHead = pHead->next;
ptr->next = nullptr;
ptr = pHead;
}
return pHead;
}
};