【Question】
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
无环的话,必定最后一个节点指向NULL。有环的话,肯定会指向前面的节点。这一个不动步长的节点,一个每次移动一个节点,另一个每次移动两个节点,有环的话总会在一个接点处相遇。
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *first,*second;
first=head;
second=head;
while(second!=NULL)
{
first=first->next;
second=second->next;
if(second==NULL) return false;
second=second->next;
if(first==second&&first!=NULL) return true;
}
return false;
}
};