Question
Given a linked list, determine if it has a cycle in it. 判断链表是否有环
Algorithm
用两个指针,一快一慢,如果它们会在某一个地方相遇则证明有环
Accepted Code
class Solution {
public:
bool hasCycle(ListNode
*head) {
if(head
==NULL || head
->next
==NULL)
return false;
ListNode
*slow
=head;
ListNode
*fast
=head;
while(fast
!=NULL && fast
->next
!=NULL)
{
fast
=fast
->next
->next;
slow
=slow
->next;
if(slow
==fast)
return true;
}
return false;
}
};
转载请注明原文地址: https://ju.6miu.com/read-11985.html