Linked list Cycle :
Q:Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
A: We put two points to traverse the list. P1 takes one step, P2 takes two steps. If two points meet each other, then there will be a cycle in the linked list.
Proof: We assume there is a cycle on the list .When P1 is at the begin of the cycle, P2 will be at some place of the cycle(refer to Figure 1). Since P1 takes one step, P2 takes two step, they both on the cycle, then P2 takes one step at the respective of P1, and P1 is still at the view of relative motion. As a result of this situation, P2 and P1 will meet each other at some time.
Since we provide the correctness of these algorithm. There is programs below:
bool hasCycle(ListNode *head) {
if(NULL == head){
return false;
}
if(NULL == head->next)
return false;
if(NULL == head->next->next){
if(head == head->next->next)
return true;
return false;
}
ListNode* slow = head->next;
ListNode* fast = head->next->next;
while(fast != NULL && fast->next!= NULL){
if(slow == fast){
return true;
}
slow = slow->next;
fast = fast->next->next;
}
return false;
}