Problem:
I: Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
II:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Solutions:
A typical problem which can be solved by two pointers, one of which is faster and the other one is slower.
Program:
I (Accepted in one time)
bool hasCycle(ListNode *head) {
if(head==NULL) return false;
if(head->next==NULL) return false;
if(head->next==head) return true;
ListNode *slow=head, *fast=head->next->next;
while(1){
if(fast==slow) return true;
if(fast==NULL || fast->next==NULL || fast->next->next==NULL) return false;
slow=slow->next;
fast=fast->next->next;
}
}
II
ListNode *detectCycle(ListNode *head) {
if(head==NULL) return NULL;
if(head->next==NULL) return NULL;
if(head->next==head) return head;
ListNode *slow=head, *fast=head;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(fast==slow) break;
}
if(fast==NULL || fast->next==NULL) return NULL;
//Find the intersection node.
slow=head;
while(fast!=slow){
slow=slow->next;
fast=fast->next;
}
return fast;
}