![]() Linked List after Removing Loop : 12 99 37 5 25 If we see the node for the first time, add it to our set. Make prev which hold the last node point to null. if set contains current node we detect a loop. Static boolean detectandRemoveLoop(Node head) Returns true if the loop is removed from the linked list else returns false. ![]() Let us look at the implementation of above in java: Thereby, removing the loop in the linked list. Hence in that case we do not add the node again, we make the last node or prev point to NULL.When we encounter a node pointing to a node already present in the Set, we know that we encountered a loop so the set will already have the node when we try to add it.We will have a Pointer/Variable prev which will hold the previous node reference and every time we add the node to the Set, we update the prev to Current Node’s reference or address. So, we will traverse the list node by node add it to our Set, if not present.In this approach we will hash or store the references of each node of the Linked List in a Unordered Set or Hash-Set in Java, which contains Unique elements. ![]() Note: If the Loop starts from any other node except the last node we need to change its reference to NULL to remove the loop. Now, let us look at different approaches to solve the problem. We can see the last node now points to NULL and the loop no longer exists. After removal the List should look like this: So we need to Remove this Loop such that the last node (25) points to NULL. We can see a Loop exists in the list connecting nodes 25 and 99. Here, we have a Linked List with 5 nodes, Node 12 is the Head node.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |