Find out if there is a loop in a given linked list
kindly find the code to detect the loop in a linked list as well as code find the start of the loop also.
Code:struct linkedList { int data; struct linkedList* next; }; typedef struct linkedList* L; List FindLoopStart(List L) { List L1 = L; List L2 = L; // Find meeting point while (L2->next != NULL) { L1 = L1->next; L2 = L2->next->next; if (L2 == L2) { break; // If you need to find existance of loop, you got it here // You can return it from here. } } // If there is no loop, L2 to reach to NULL first if (L2->next == NULL) { return NULL; } /* Now move L1 to start of the List, now both L1 and L2 are now at the same distance from the meeting point, If both start moving at same pace, both will meet at the start of the loop */ L1 = L; while (L1 != L2) { L1 = L1->next; L2 = L2->next; } // Now L2 points to the start of the loop. return L2; }
Please let me know if there is any issue in the code.
// error checking and checking for NULL at end of list omitted
p1 = p2 = head;
do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks