给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
感觉自己是铁five了
vector搜索
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
vector<ListNode*> lis;
while(head!=NULL){
auto it=find(lis.begin(),lis.end(),head);
if(it!=lis.end())return *it;
lis.push_back(head);
head=head->next;
}
return NULL;
}
};
快慢指针
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast=head,*slow=head,*meet;
while(fast!=NULL){
fast=fast->next;
if(fast!=NULL)fast=fast->next;
slow=slow->next;
if(fast==slow)break;
}
if(fast==NULL)return NULL;
fast=head;
while(fast!=slow){
fast=fast->next;
slow=slow->next;
}
return fast;
}
};