Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wataruoguchi/3383e77cc1e1c7b048dad1e52bd0da92 to your computer and use it in GitHub Desktop.
Save wataruoguchi/3383e77cc1e1c7b048dad1e52bd0da92 to your computer and use it in GitHub Desktop.
Detect and Remove Loop in a Linked List
// https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
function printList(root) {
let tmp = root;
let arr = [];
while (tmp) {
arr.push(tmp.val);
tmp = tmp.next;
}
return arr;
}
class Node {
constructor(val, next) {
this.val = val;
this.next = next;
}
}
function printNNodes(N) {
return function printNodes(root) {
let tmp = root;
let arr = [];
let idx;
for (idx = 0; idx < N; idx++) {
if (tmp) {
arr.push(tmp.val);
tmp = tmp.next;
}
}
return arr;
}
}
function removeLoopInNodes(root) {
let tmp = root;
const nextPointerStack = [];
while (tmp) {
if (nextPointerStack.indexOf(tmp.next) >= 0) tmp.next = null;
nextPointerStack.push(tmp.next);
tmp = tmp.next;
}
return root;
}
const print6Nodes = printNNodes(6);
const ex1 = new Node(1, new Node(3, new Node(4)));
// Looped
ex1.next.next.next = ex1.next;
console.log(print6Nodes(ex1).join(',') === '1,3,4,3,4,3');
removeLoopInNodes(ex1);
console.log(print6Nodes(ex1).join(',') === '1,3,4');
const ex2 = new Node(1, new Node(8, new Node(3, new Node(4))));
// Looped
ex2.next.next.next.next = ex2.next;
console.log(print6Nodes(ex2).join(',') === '1,8,3,4,8,3');
removeLoopInNodes(ex2);
console.log(print6Nodes(ex2).join(',') === '1,8,3,4');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment