DEV Community

Cover image for Linked List cycle
urvashi soni
urvashi soni

Posted on

4 1

Linked List cycle

We will use Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm.

Overview

  1. We will use a 2-pointer technique where 1 pointer will be fast and the other pointer will be slow.
  2. The whole idea is based on the principle that if there is a cycle in the Linked List, at some point both the pointers will meet each other, else one of them ( or its next ) will be NULL.

Let's implement using Javascript. -

  1. The input here will be a Linked List.
  2. First of all, we will check if the Linked List is empty or has just 1 node. There will not be any cycle definitely in both of the cases.
  3. Next, we will define 2 pointers, as mentioned above. First will be a slow pointer and the second will be the fast pointer i.e. while traversing, when the slow pointer will move one step ahead, the fast pointer will move two steps ahead.
  4. We will keep traversing until slow and fast is not equal or one of them ( or its next ) is not NULL.
  5. If fast and slow becomes equal, then it means there is a cycle.
  6. If either of the slow or fast pointer ( or its next ) becomes NULL, it means there is no cycle in the Linked List.
var hasCycle = function(head) {
    if (head === null || head.next === null) {    // Point 2
        return false;                             // Point 6
    }
    let slow = head.next;                         // Point 3
    let fast = head.next.next;
    while(slow!==fast) {                          // Point 4
        slow = slow.next;
        if (fast == null || fast.next === null) { // Point 4,5
            return false;                         // Point 6
        }
        fast = fast.next.next;
    }
    return true;                                  // Point 5
};
Enter fullscreen mode Exit fullscreen mode

Please note that for point 6, we check only fast node for NULL value because at any point fast will be ahead of slow and it will visit every node before the slow node.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay