Open In App

JavaScript Program to Remove Loop in a Linked List

Last Updated : 25 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A linked list is a collection of nodes that contain both a data element and a reference (or pointer) to the next node in the collection.  A common concern with linked lists is having loops and cycles. When one of the nodes in the linked list points towards any of its previous nodes leading to an infinite cycle. While traversing the list, this can cause problems due to the loop.

There are several approaches to removing the loop in a linked list using JavaScript which are as follows:

Hashing Approach

It uses a set to record visited entries when it is travelling along. For instance, if there exists a node that has already been placed on the set while travelling through the list means that there is a loop. To remove the loop after detecting it, we need to initialize the last node’s next pointer as null.

Algorithm:

  • Keep a record of the visited nodes using a set.
  • Adding each node to the set when traversing the list.
  • The presence of a node in the set indicates that there is a loop.
  • Make sure that the last node’s next pointer is `null` to eliminate the loop.

Example: To demonstrate removing loop in a linked list using the hashing approach.

JavaScript
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

// Function to print the linked 
// list up to 20 nodes for simplicity
function printList(head) {
    let current = head;
    let count = 0;
    while (current && count < 20) {
        console.log(current.value);
        current = current.next;
        count++;
    }
}

// Function to create a 
// loop in the linked list
function createLoop(head, loopIndex) {
    let current = head;
    let loopNode = null;
    let index = 0;

    while (current.next) {
        if (index === loopIndex) {
            loopNode = current;
        }
        current = current.next;
        index++;
    }
    current.next = loopNode;
    // Create loop by linking 
    // the last node to the loopNode
}

// Example usage
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

// Create a loop at 
// index 2 (Node with value 3)
createLoop(head, 2);

console.log("Before removing loop:");
printList(head);


// Function to remove loop
// using Hashing Approach
function removeLoopHashing(head) {
    const visitedNodes = new Set();
    // Set to keep track of visited nodes
    let current = head;
    let prev = null;

    // Traverse the list
    while (current) {
        // If current node is already 
        // visited, loop detected
        if (visitedNodes.has(current)) {
            prev.next = null;
            // Remove loop by setting 
            // the previous node's next to null
            console.log('Loop removed');
            return;
        }
        visitedNodes.add(current);
        prev = current;
        current = current.next;
    }
}

// Removing loop 
// using Hashing Approach
removeLoopHashing(head);
console.log("\nAfter removing loop:");
printList(head);

Output
Before removing loop:
1
2
3
4
5
3
4
5
3
4
5
3
4
5
3
4
5
3
4
5
Loop removed

After removing loop:
1
2
3
4
5

Time Complexity: O(n)

Space Complexity: O(n)

Floyd’s Cycle Detection Algorithm (also known as the “Tortoise and Hare” approach)

This technique involves two pointers moving at different velocities in detection of loops. To erase a cycle after its identification within Floyd’s tortoise-hare algorithm, just find out where the beginning point was located when starting from head and update the next pointer of last node inside this cycle into null.

Algorithm:

  • Employ two pointers, ‘slow’ and ‘fast’.
  • Move ‘slow’ by one step and ‘fast’ by two steps during every iteration.
  • If they meet, it means there is a cycle at this point
  • While one of them retraces his steps back to head, move both pointers forward until their paths cross again
  • Break the loop by making null the next pointer of any node just before its start

Example: To demonstrate removing the loop in a linked list using Floyd’s tortoise-hare algorithm in JavaScript.

JavaScript
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

// Function to print the linked 
// list up to 20 nodes for simplicity
function printList(head) {
    let current = head;
    let count = 0;
    while (current && count < 20) {
        console.log(current.value);
        current = current.next;
        count++;
    }
}

// Function to create a 
// loop in the linked list
function createLoop(head, loopIndex) 
{
    let current = head;
    let loopNode = null;
    let index = 0;

    while (current.next) {
        if (index === loopIndex) 
        {
            loopNode = current;
        }
        current = current.next;
        index++;
    }
    current.next = loopNode; 
    // Create loop by linking 
    // the last node to the loopNode
}

// Example usage
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

// Create a loop at 
// index 2 (Node with value 3)
createLoop(head, 2);

console.log("Before removing loop:");
printList(head);
// Function to remove loop using 
// Floyd's Cycle Detection Algorithm
function removeLoopFloyds(head)
 {
    let slow = head;
    let fast = head;

    // Use slow and fast 
    // pointers to detect loop
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;

        // If slow and fast 
        // pointers meet, loop detected
        if (slow === fast) {
            removeLoop(head, slow); 
            // Remove loop
            console.log('Loop removed');
            return;
        }
    }
}

// Helper function to 
// remove loop once detected
function removeLoop(head, loopNode)
 {
    let ptr1 = head;
    let ptr2 = loopNode;

    // Find the start
    //  of the loop
    while (ptr1 !== ptr2) {
        ptr1 = ptr1.next;
        ptr2 = ptr2.next;
    }

    // Find the node just before
    //  the start of the loop
    let prev = ptr2;
    while (prev.next !== ptr1) {
        prev = prev.next;
    }

    // Disconnect the loop
    prev.next = null;
}

// Removing loop using Floyd's 
// Cycle Detection Algorithm
removeLoopFloyds(head);
console.log("\nAfter removing loop:");
printList(head);

Output
Before removing loop:
1
2
3
4
5
3
4
5
3
4
5
3
4
5
3
4
5
3
4
5
Loop removed

After removing loop:
1
2
3
4
5

Time Complexity: O(n)

Space Complexity: O(1)

Marking Approach

In this method, flagging nodes as visited indicates that they have been visited before. If some entry is already flagged as being visited before, it means there exists a loop. After identifying such scenarios represented by detected loops, then their removal will follow by setting next pointer’s last node inside given loop into nulls only.

Algorithm:

  • Flagging each node after iterating through with `visited`.
  • If discovered as being visited, denotes that there exists a loop
  • However, reset all links between nodes prior to this beginning of such circularity so as not produce cycles

Example: To demonstrate removing the loop in a linked list using the marking approach.

JavaScript
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

// Function to print the linked 
// list up to 20 nodes for simplicity
function printList(head) {
    let current = head;
    let count = 0;
    while (current && count < 20)
     {
        console.log(current.value);
        current = current.next;
        count++;
    }
}

// Function to create a 
// loop in the linked list
function createLoop(head, loopIndex)
 {
    let current = head;
    let loopNode = null;
    let index = 0;

    while (current.next) {
        if (index === loopIndex) 
        {
            loopNode = current;
        }
        current = current.next;
        index++;
    }
    current.next = loopNode;
     // Create loop by linking the
     //  last node to the loopNode
}

// Example usage
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

// Create a loop at 
// index 2 (Node with value 3)
createLoop(head, 2);

console.log("Before removing loop:");
printList(head);

// Function to remove 
// loop using Marking Approach
function removeLoopMarking(head)
 {
    let current = head;
    let prev = null;

    // Traverse the list
    while (current) {
        // If current node is 
        // visited, loop detected
        if (current.visited) {
            prev.next = null; 
            // Remove loop by setting the 
            // previous node's next to null
            console.log('Loop removed');
            return;
        }
        current.visited = true;
        // Mark current node as visited
        prev = current;
        current = current.next;
    }
}

// Removing loop 
// using Marking Approach
removeLoopMarking(head);
console.log("\nAfter removing loop:");
printList(head);

Output
Before removing loop:
1
2
3
4
5
3
4
5
3
4
5
3
4
5
3
4
5
3
4
5
Loop removed

After removing loop:
1
2
3
4
5

Time Complexity: O(n)

Space Complexity: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads