一、题目
题目描述
对于一个给定的链表,返回环的入口节点,如果没有环,返回null
拓展:
你能给出不利用额外空间的解法么?
二、思路
1、一个快指针、一个慢指针
2、再跑第二次
3、注意fast!=NULL && fast->next!=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){
return head;
}
ListNode *fast=head,*slow=head;
int flag=0;
while(fast!=NULL && fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
flag=1;
break;
}
}
if(flag==0){
return NULL;
}
ListNode *ptr=head;
while(ptr!=fast){
ptr=ptr->next;
fast=fast->next;
}
return ptr;
}
};