InterviewSolution
| 1. |
How To Check If Linked List Contains Loop In Java? How To Find The Starting Node Of The Loop? |
|
Answer» This is another interesting linked list problem which can be solved using the two pointer approach discussed in the FIRST question. This is also known as tortoise and hare algorithm. Basically, you have two pointers fast and slow and they move with different speed i.e. fast MOVES 2 notes in each iteration and slow moves ONE node. If linked list contains cycle then at some point in TIME, both fast and slow pointer will meet and point to the same node, if this didn't happen and one of the pointer reaches the end of linked list means linked list doesn't contain any loop. This is another interesting linked list problem which can be solved using the two pointer approach discussed in the first question. This is also known as tortoise and hare algorithm. Basically, you have two pointers fast and slow and they move with different speed i.e. fast moves 2 notes in each iteration and slow moves one node. If linked list contains cycle then at some point in time, both fast and slow pointer will meet and point to the same node, if this didn't happen and one of the pointer reaches the end of linked list means linked list doesn't contain any loop. |
|