- 判断环形链表
对应题目:力扣141
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast=head,*slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)//为环形链表
return true;
}
return false;
}
};
- 寻找环形链表入口
对应题目:力扣142题
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast=head,*slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){//快慢指针相遇
ListNode *temp1=slow,*temp2=head;
while(temp1!=temp2){
temp1=temp1->next;
temp2=temp2->next;
}
return temp1;//入口点
}
}
return NULL;
}
};