26. Write a progrm to find loop detect and remove from linked list.
int detectLoop(struct node *head)
{
struct node *slow = list, *fast = head;
while (slow && fast && fast->next )
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
printf("\r\nLoop detected in linked list \r\n");
removeloop(slow, head);
}
}
return 0;
}
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;
ptr1 = ptr1->next;
}
}
ptr2->next = NULL;
}
Ramya
6 Sep, 2019 6:19 PM
{
struct node *slow = list, *fast = head;
while (slow && fast && fast->next )
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
printf("\r\nLoop detected in linked list \r\n");
removeloop(slow, head);
}
}
return 0;
}
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;
ptr1 = ptr1->next;
}
}
ptr2->next = NULL;
}
Report Error
Report Error
Please Login First Click Here