1. Start reversing the list. If you reach the head, then there is a loop.
But this changes the list. So, reverse the list again.
2. Second solution is called Hare and Tortoise approach. Basically have 2 ptrs both
pointing to the start of the list. Increment first pointer by one and
second pointer by 2. After each increment comapre if they are equal. They will meet if there is a loop.
p1 = p2 = head;
do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
3. Hash all seen nodes and compare the next node with the nodes in the hash. If a node is already present in the hash then there is a loop.
No comments:
Post a Comment