class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL)
return false;
ListNode* fast=head->next,*slow=head;
while(fast&&slow&&fast->next)
{
if(fast==slow)
return true;
slow=slow->next;
fast=fast->next->next;
}
return false;
}
};141. Linked List Cycle
最新推荐文章于 2025-05-07 22:36:04 发布
本文介绍了一种使用快慢指针的方法来检测链表中是否存在循环。通过两个速度不同的指针遍历链表,如果存在循环,则快指针最终会追上慢指针;反之则不存在循环。
821

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



