I have a LinkedList class in Javascript(ES6) which has all the related helper methods (like insert, remove, update etc). Additionally, I want to implement a reusable forEach loop that can be used to iterate over the linked list.
class LinkedList(){
constructor(){
//linked list
this.list = null;
}
//Inserting a node at the first position
insertFirst(data) {
let node = new Node(data);
if (this.list) {
node.next = this.list;
this.list = node;
}
else {
this.list = node;
}
}
//...
//Other helper methods...
//...
forEach(){
//loop implementation goes here
}
}
//Node class for creating a new Node
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
For instance, this is the linked list with 'n' nodes,
this.list = {
data: 10,
next: node1
};
let node1 = {
data: 20,
next: node2
};
let node2 = {
data: 20,
next: node3
};
So and so...
I should be able to iterate the list like an array forEach and perform any action at the node level, like below
const list = new LinkedList();
//inserted 10 nodes using list.insertFirst() method
list.forEach(node => {
console.log(node.data);
});
What is the best possible way to achieve this?