/**
* 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){
return false;
}
if(head->next==NULL){
return false;
}
ListNode*p1=head;
ListNode*p2=head;
while(true){
p1=p1->next;
if(p2->next==NULL||p2->next->next==NULL){
return false;
break;
}
p2=p2->next->next;
if(p2==p1){
return true;
break;
}
}
}
};