Similar Problems

Similar Problems not available

How to detect cycle in a linked list ? - Leetcode Solution

Companies:

LeetCode:  How to detect cycle in a linked list ? Leetcode Solution

Difficulty: Unknown

Topics: linked-list  

How to find cycle in a linked list ?

There are multiple ways to find cycle in a linked list. However, the most common way to find cycle in a linked list is using Floyd’s cycle detection algorithm This algorithm is also known as the hare and tortoise algorithm, since it uses two pointers one of which is slow and one of which is fast.

Algorithm

Step 1: Initialize two pointers one fast_pointer, and one slow_pointer to the start of the linked list.
Step 2: While slow_pointer does not reach the end do the following :
Step 3: Move slow_pointer by one step and fast_pointer by two steps
Step 4: If slow_pointer and fast_pointer meet anywhere, it means that there is a cycle in the linked list.

If the slow_pointer reaches the end, and slow_pointer and fast_pointer do not meet ever, it means that there is no cycle in the linked list.

See the flowchart below for the steps:
FlowChart

How to detect cycle in a linked list ? Solution Code

1