题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:
快慢指针的交点不一定的是入口点,但是重链表的开头到交点的具体和交点绕环再到交点的距离是相等的
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* head)
{
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
break;
}
if(fast != slow || fast == NULL || fast->next == NULL)
return NULL;
slow = head;
while(slow != fast)
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
};