I know it is a FAQ and have a lot of answers such as Interview: Remove Loop in linked list - Java. but I have the following concerns. If I am wrong, please point out and would you please direct me to a link with right answer?
- If want to not only detect but also remove the cycle, should change
if (fast_ptr==slow_ptr || fast_ptr->_next == slow_ptr)
toif (fast_ptr==slow_ptr)
; because there is only one entrance point. - Should consider the case when entrance if head. i.e. the case: 1->2->3->4->1->2->3->4..., I never see any link show this case. Am I wrong?
Here is my code:
bool determine_remove_Cycle_list(sIntElement *head){
sIntElement* slow_ptr = head;
sIntElement* fast_ptr = head;
while(true){
if (!fast_ptr || !(fast_ptr->_next)) return false;
slow_ptr = slow_ptr->_next;
fast_ptr = fast_ptr->_next->_next;
if (fast_ptr==slow_ptr)//fast_ptr->_next == slow_ptr is not checked
break; //is cycle
}
fast_ptr = head;
while(fast_ptr->_next != slow_ptr->_next){
fast_ptr = fast_ptr->_next;
slow_ptr = slow_ptr->_next;
}
}
if (slow_ptr == head){ //special case: start of the cycle is head,
while (slow_ptr->_next != head){
slow_ptr = slow_ptr->_next;
}
slow_ptr->_next = NULL; //slow is the node before the start point
return true;
}