快慢指针
若快指针和慢指针相遇则代表有环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast=head;
ListNode *slow=head;
if(head==NULL)
return false;
while(fast->next&&fast){
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}
};
不断删除节点法
从一个节点开始,一个一个不断删除,若有环,则会出现p=p->next的情况,若无环,在某个时刻会出现p->next==NULL的情况,通过递归实现。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL){
return false;
}
if(head->next==head){
return true;
}
ListNode *tmp=head->next;
head->next=head; //自己指向自己,意味着把自己删除
return hasCycle(tmp);
}
};