LET'S TALK TECHNICAL

This blog is intended to help people prepare for the job interviews and improve their analytical skills. We have posted difficult datastructures and algorithm questions and puzzles. Interview experiences section is for the people to post their interview experiences.Views expressed here are of their personal and the blog author doesn't take any responsibility for the same.

-

Followers

Jobs

Saturday, February 2, 2008

Given a singly linked list, determine whether it contains a loop or not.

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

Popular Posts