
使用快慢指针,快的一次走两步,慢的一次走一步,如果有环,快的会追上慢的。
/**
* 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;
ListNode* fast=head;
ListNode* slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
};
本文介绍了一种使用快慢指针检测链表中是否存在环的高效算法。通过一次遍历,快指针每次移动两步,慢指针每次移动一步,如果两者相遇则表明链表有环。

1475

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



