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 to Swap Two Elements in a Linked List
We are given a linked list and the task is to swap two elements in a linked list without disturbing their links. There are multiple ways to swap. It can be done by swapping the elements inside the nodes, and by swapping the complete nodes. Example: Input: list = 10 -> 11 -> 12 -> 13 -> 1
5 min read
JavaScript Program to Print Even Numbers in a Linked List
A linked list is a data structure that stores the values at different memory locations concerning the next memory block of stored value. You can get all the even numbers stored in a linked list using the below methods. Table of Content Using While LoopUsing RecursionUsing While LoopTo print even num
2 min read
Delete Operations in Doubly Linked List using JavaScript
This article will demonstrate how to perform delete operations in a Doubly Linked List Data Structure using JavaScript. We will see different approaches to deleting elements from the Doubly Linked List. Steps to Delete Element Node from Doubly Linked ListA doubly linked list has two pointers that li
11 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 Middle Of Linked List
Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5If there are even nodes, then there would be two middle nodes, we need to delete the second middle elemen
3 min read
Javascript Program for Clockwise rotation of Linked List
Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
4 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