思路:用快慢指针来遍历链表,如果最后快指针跑到慢指针指向的节点后面去了,说明链表存在循环。
code:
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head){
ListNode *fast=head->next,*slow=head;
while(fast&&slow){
if(fast->next == NULL)return false;
if(fast == slow || fast->next == slow) return true;
slow = slow->next;
fast = fast->next->next;
}
}
return false;
}
};