In JavaScript, copying all nodes of a linked list can be done by creating a duplicate of the entire linked list by maintaining the structure of each element. We can copy all nodes using Recursion and Map.
Using Recursion
In this approach, we use a recursive function recursiveFn to traverse the original linked list and create a new linked list with copied nodes. The recursion continues till the entire original linked list is traversed, which results in a deep copy of the original linked list.
Example: The example below uses Recursion to copy all linked list nodes.
class Node { constructor(data) {
this .data = data;
this .next = null ;
}
} let 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);
let original = head; console.log( "Original Nodes: " )
while (original) {
process.stdout.write
(original.data.toString());
original = original.next;
if (original) {
process.stdout.write( " -> " );
}
} console.log(); function recursiveFn(oNode) {
if (!oNode) return null ;
let temp = new Node(oNode.data);
temp.next =
recursiveFn(oNode.next);
return temp;
} let cTemp = recursiveFn(head); let cTemp2 = cTemp; console.log( "Copied Nodes: " )
while (cTemp2) {
process.stdout.write
(cTemp2.data.toString());
cTemp2 = cTemp2.next;
if (cTemp2) {
process.stdout.write( " -> " );
}
} console.log(); |
Original Nodes: 1 -> 2 -> 3 -> 4 -> 5 Copied Nodes: 1 -> 2 -> 3 -> 4 -> 5
Using Map
In this approach, a new linked list is created by iterating through the original linked list and also using a Map to associate each node in the original list with its corresponding copied node. This Map is then uses to link the copied nodes and create a deep copy of the original linked list.
Syntax:
let myMap = new Map();
Example: The example below uses a Map to copy all linked list nodes.
class Node { constructor(data) {
this .data = data;
this .next = null ;
}
} let 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);
let curr = head; console.log( "Original Node: " )
while (curr) {
process.stdout.write
(curr.data.toString());
curr = curr.next;
if (curr) {
process.stdout.write( " -> " );
}
} console.log(); let copyHead = new Node(head.data);
let map = new Map([[head, copyHead]]);
let temp1 = head.next; let temp2 = copyHead; while (temp1) {
temp2.next = new Node(temp1.data);
temp2 = temp2.next;
map.set(temp1, temp2);
temp1 = temp1.next;
} temp1 = head; temp2 = copyHead; while (temp1) {
if (temp1.next) {
temp2.next = map.get(temp1.next);
}
temp1 = temp1.next;
temp2 = temp2.next;
} let temp3 = copyHead; console.log( "Copied Node: " )
while (temp3) {
process.stdout.write
(temp3.data.toString());
temp3 = temp3.next;
if (temp3) {
process.stdout.write( " -> " );
}
} console.log(); |
Original Node: 1 -> 2 -> 3 -> 4 -> 5 Copied Node: 1 -> 2 -> 3 -> 4 -> 5