题目描述:
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
。
说明:不允许修改给定的链表。
思路:使用快和慢两个指针,如果说最后在快指针没有走出环之前二者相遇了,则说明,肯定有环,并且此时的慢指针和快指针走的距离之差就是环的长度,/因此可以先通过这个方式把环的长度计算出来,然后再让快指针先走环的长度个,然后慢指针再继续走,当二者再一次相遇的时候就是环入口的位置
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL || head->next==head)
return head;
ListNode *fast=head;
ListNode *slow=head;
int fastSteps=0, slowSteps=0;
while(fast!=NULL){
if(fast->next==NULL)
return NULL;
else
fast=fast->next->next;
slow=slow->next;
fastSteps+=2;
slowSteps+=1;
if(fast==slow)
break;
}
if(fast==NULL)
return NULL;
int length=fastSteps-slowSteps;
fast=head;
for(int i=0; i<length; ++i)
fast=fast->next;
slow=head;
while(fast!=slow){
fast=fast->next;
slow=slow->next;
}
return fast;
}
};