题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
(1)算法思想:
取快、慢两个指针,快指针一次走两步,慢指针一次走一步,如果存在circle,则快慢指针一定会相遇,否则不会相遇。
(2)代码如下:
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head)return false;
if(!head->next)return false;
ListNode *fast=head,*slow=head;
while(fast->next&&fast->next->next){
fast=fast->next->next;
slow=slow->next;
if(fast->val==slow->val)
return true;
}
return false;
}
};