Write code to detect a loop in a linked list.
Approach:
Keep 2 pointers at the head, say front and back.
Now move the front twice the speed as the back, if before back completing the one loop, the front pointer reaches back or overtakes it then there is loop in the singly link list.
Approach:
Keep 2 pointers at the head, say front and back.
Now move the front twice the speed as the back, if before back completing the one loop, the front pointer reaches back or overtakes it then there is loop in the singly link list.
You can find out the cycle or loop in a single linked list by using two pointer approach.
ReplyDeleteBelow link can be useful to find out the algorithm to find cycle or loop in linked list
find out the cycle or loop in a single linked list in java