1.题目
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
2.Code
之前写过这个题目的题解及证明,链接在这:链表环入口
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x):val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead){
if(pHead == NULL || pHead->next == NULL || pHead->next->next == NULL)
return NULL;
ListNode* fast = pHead->next->next;
ListNode* slow = pHead->next;
while(slow != fast){
if(fast->next == NULL || fast->next->next == NULL)
return NULL;
fast = fast->next->next;
slow = slow->next;
}
fast = pHead;
while(slow != fast){
fast = fast->next;
slow = slow->next;
}
return slow;
}
};