Implement a Linked List
Anónimo
class Node { //class to create node object constructor (value) { this.value = value; this.next = null; } } class LinkedList { //class for implementing Linked List functions constructor () { //Initialization of Linked List this.head = null; this.size = 0; } //function to add node in existing list addNode (value) { let node = new Node(value); if (this.head === null) { this.head = node; } else { let currentNode = this.head; while (currentNode.next) { currentNode = currentNode.next; } currentNode.next = node; } this.size++; } //function to reverse the existing list reverseList () { if (this.head === null) { console.log("Linked List is empty"); } else { let currentNode = this.head, prevNode, nextNode; while (currentNode) { nextNode = currentNode.next; currentNode.next = prevNode; prevNode = currentNode; currentNode = nextNode;; } this.head = prevNode; } } //function to add the node at specified index in the existing list addNodeAtIndex(index, value) { if (this.head === null) { console.log("Linked List is empty"); return; } if (index this.size) { console.log("Index not in range"); return; } let node = new Node(value), currentNode = this.head, prevNode = null; if (index === 0) { node.next = currentNode; this.head = node; } else { for (let i=0; i = this.size) { console.log("Index not in range"); return; } let currentNode = this.head, prevNode; if(index === 0) { currentNode = currentNode.next; this.head = currentNode; } else { for (let i=0; i'; currentNode = currentNode.next; } console.log(list); } } } let llobj = new LinkedList(); //object for classLinkedList //Addition of 10 elements in the list for (let i=0; i<10; i++) { llobj.addNode(i*10); //calling addNode function to add node in the list } //printing the list llobj.printList(); //you can call any function of class LinkedList via its object "llobj" with "." and the name of function.