![]() ![]() ![]() Here are the images displaying the use of Floyd’s cycle-finding algorithm:Īs we can see, the two pointers will ultimately meet at a particular node in the loop. Thus, the execution will stop and the code will show the output as ‘loop is present’. When this happens, instead of finding a null value, it will be ptr1 = ptr2. Why is this? Because once the pointers find a loop, they will begin traversing in the loop with varying speeds, therefore ultimately meeting. Additionally, at some stage during traversing the list, the two pointers will eventually meet at a particular node. Instead, they will enter the loop and cross over there. ![]() As you may have already guessed, the pointers will not reach NULL. The second scenario is the presence of a loop in the linked list. In this case, a null value is encountered and we stop the execution and demonstrate the output of the code as ‘no loop’. Note that if there is an even number or an odd number of nodes in the linked list, ptr2→ will still become null. This means that ptr2 will become null even if there are several nodes. In the first scenario, there will be no loop in the list and therefore, ptr2→ will point to NULL since ptr2 moves two nodes at a go. Step 3: Since ptr2 moves faster than ptr1, it will reach the end of the linked list sooner.Īfter reaching the end of the list, there are two possible scenarios. Step 2: The two pointers start traversing the list, ptr1 one node at a time, and ptr2 two nodes at a time. Step 1: Both the pointers (ptr1 and ptr2) begin by pointing at the first node. In practice, Floyd's cycle-finding algorithm works as shown below: The algorithm is also sometimes called the hare-tortoise algorithm as a reference to the children's story about the race between the hare and the tortoise. It uses two pointers with one moving slower than the other as it traverses the list. And the quickest way to do this is by using Floyd’s cycle-finding algorithm. The first step in diagnosing the problem is to detect if the linked list indeed has a loop. Let’s discuss this in detail How to find a loop in a linked list Approach 1: Floyd’s cycle-finding algorithm There are several ways we can remove a loop in a linked list. Since we now know that the linked list has a loop in it, how do we go about removing it? Note that removing the loop will resemble something like this: 1 → 3 → 5 → 7 → 9 → NULL. We can also see that the last node redirects back to the first node. In the figure above, we can see that the linked list has a loop beginning at node 3 and contains 4 nodes, i.e., 3, 5, 7 and 9. Removing a loop in a linked list means making the last node point to NULL and not to other nodes in the list. A linked list that contains a loop will have the last node pointing to another node in the same list, rather than pointing to the NULL. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |