JavaScript Program to Remove Loop in a Linked List
Last Updated :
25 Apr, 2024
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);
OutputBefore 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);
OutputBefore 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);
OutputBefore 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)
Similar Reads
JavaScript Program to Remove Empty Node from Linked List JavaScript allows us to remove the empty node from the linked list by traversing through the linked list and finding each empty node. There are several approaches available in JavaScript through which this can be achieved which are as follows: Table of Content Iterative ApproachRecursive ApproachIte
3 min read
Javascript Program For Removing Every K-th Node Of The Linked List Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples :Input: 1->2->3->4->5->6->7->8 k = 3Output: 1->2->4->5->7->8As 3 is the k-th node after its deletion
3 min read
JavaScript Linked List Programs JavaScript Linked List Programs contain a list of articles based on programming. Linked List is a linear data structure that stores data in linearly connected nodes. Linked lists store elements sequentially, but doesnât store the elements contiguously like an array. S. NoArticles1JavaScript Program
5 min read
Javascript Program To Delete Alternate Nodes Of A Linked List Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3.Method
4 min read
Javascript Program For Removing Duplicates From A Sorted Linked List Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
8 min read
Javascript Program For Removing Duplicates From An Unsorted Linked List Given an unsorted Linked List, the task is to remove duplicates from the list. Examples: Input: linked_list = 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21 Output: 12 -> 11 -> 21 -> 41 -> 43 Explanation: Second occurrence of 12 and 21 are removed. Input: linked_list = 12 ->
5 min read
Javascript Program For Removing Middle Points From a Linked List Of Line Segments Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line.Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linked
4 min read
Javascript Program To Delete N Nodes After M Nodes Of A Linked List Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.Difficulty Level: Rookie Examples:Input:M = 2, N = 2Linked List: 1->2->3->4->5->6->7->8Output:Linked List:
3 min read
Javascript Program For Deleting A Node In A Doubly Linked List Pre-requisite: Doubly Link List Set 1| Introduction and InsertionWrite a function to delete a given node in a doubly-linked list. Original Doubly Linked List Approach: The deletion of a node in a doubly-linked list can be divided into three main categories: After the deletion of the head node. After
4 min read
Java Program to Implement Unrolled Linked List An Unrolled Linked List is a special type of Linked List in which each node stores an array of elements, unlike a simple linked list. Here we use an ArrayList and a constructor that initializes the size of the Unrolled Linked List. Elements are added to the first Node until it is filled and then a n
5 min read