Detect and Remove Loops in Linked List
Quick Question! Imagine you are in a train and some bogey at the back of the train has a lazy lockmaster who happens to join the link of his bogey to the Engine instead of joining it to the bogey that he is supposed to, while every other lockmaster does the job right!
Yep, now this makes some sense to me too! As you can see here, once the train starts to roll off the tracks, all sorts of trouble will start to unfold. Now how do we solve this? Well in the real world this problem could have required some heavy lifting but not here, we just need to code some stuff to rectify such an issue in a Linked List
Yes that's right, it was hard for me to imagine such a scenario too, here's a picture for better reference -
Let's get started!
Assuming we already have a function to insert nodes, let's discuss about a removing loop function
void Removeloop(Node* head)
{
// hash map to hash addresses of the linked list nodes
unordered_map<Node*, int> node_map;
// pointer to last node
Node* last = NULL;
while (head != NULL)
{
// if node not present in the map, insert it in the map
if (node_map.find(head) == node_map.end()) {
node_map[head]++;
last = head;
head = head->next;
}
// if present, it is a cycle, make the last node's next pointer NULL
else {
last->next = NULL;
break;
}
}
}
So it's quite self explanatory but i'll still give you a basic idea of what we have done here.
Using Hashmaps we create a 'node_map', we also happen to have a Next pointer pointing to a NULL value at the beginning.
Steps-
- We iterate a loop through the linked list until the last value, with each iteration our purpose is to find data values in the linked list that are not present in the hashmap and then inserting them in it one by one.
- Once we have entered all the values one by one, the loop in the Linked List will come at some point.
- The moment it comes up, our If condition to check whether the data was present in Hashmap or not will be used and no further data will be entered.
- Instead the link of Last node i.e 'Next' will point to NULL value and break the loop cycle
And there you have it! We have solved a huge crisis and made world a better place, atleast theoretically.
That's what i coded! ^_^