Consider this as a separate list and perform the following operations.
int detectloop(struct node *list) { struct node *slow_p = list, *fast_p = list; while(slow_p && fast_p && fast_p->next ) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { printf("Found Loop"); return 1; } } return 0; }
In the above code, we use two pointers: one is slow and the other is fast, slow moves one step and quickly moves two steps at a time. The time when they both meet, we can say that the linked list has a loop, otherwise not.
void removeLoop(struct node *loop_node, struct node *head) { struct node *ptr1; struct node *ptr2; ptr1 = head; while(1) { ptr2 = loop_node; while(ptr2->next != loop_node && ptr2->next != ptr1) { ptr2 = ptr2->next; } if(ptr2->next == ptr1) break; else ptr1 = ptr1->next; } ptr2->next = NULL; }
After detecting the cycle, we can use one cycle and start from the beginning and move the slow pointer to it, as usual, the speed when both pointers meet the meeting point is the beginning of the cycle, and we can break it.
source share