思路:用快慢指针来遍历链表,如果最后快指针跑到慢指针指向的节点后面去了,说明链表存在循环。
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;
}
};
本文介绍了一种使用快慢指针的方法来判断链表是否存在循环。通过两个速度不同的指针遍历链表,若存在循环则快指针最终会追上慢指针。
258

被折叠的 条评论
为什么被折叠?



