题目描述
一个链表中包含环,请找出该链表的环的入口结点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead){
// 1.先找到环中的一个节点
// 2.记录环的长度
// 3.指针先行,找到入口节点
ListNode* oneNode = oneNodeInCycle(pHead);
if(oneNode == NULL)
return NULL;
// 计算长度
ListNode* walk = oneNode->next;
int len = 1;
while(oneNode != walk){
++len;
walk = walk->next;
}
// 指针先行,找到入口节点
ListNode* fast = pHead;
ListNode* slow = pHead;
while(len--){
fast = fast->next;
}
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
// 返回环中的一个节点或NULL
ListNode* oneNodeInCycle(ListNode* pHead){
ListNode* fast = pHead;
ListNode* slow = pHead;
while(pHead && pHead->next && pHead->next->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return fast;
}
return NULL;
}
};