取巧
class Solution {
public:
const int INF=1e9;
bool hasCycle(ListNode *head) {
bool res=false;
auto p=head;
while(p)
{
if(p->val==INF)
{
res=true;
break;
}
p->val=INF;
p=p->next;
}
return res;
}
};
双指针
/**
* 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) {
bool res=true;
if(head==NULL) return false;
auto i=head,j=head;
do
{
i=i->next;
if(j->next&&j->next->next) j=j->next->next;
else
{
res=false;
return res;
}
}while(i!=j);
return res;
}
};