Linked List : Creation & multiple operations

Run Settings
LanguageJavaScript
Language Version
Run Command
// 10-->5-->16 // let myLinkedList = { // head:{ // value: 10, // next:{ // value:5, // next:{ // value:16, // next:null // } // } // } // } // 1-->10-->99-->5-->16-->88 class LinkedList { // creating linked list with only 1 (head) value constructor(value){ this.head = { value: value, next: null } this.tail = this.head; this.length = 1; } append(value){ // function to add value one by one to the end of the linked list const newNode = { value: value, next: null }; this.tail.next = newNode; // tail's reference value will point to the new node this.tail = newNode; // tail value will be updated with the value of new node this.length++; return this; } prepend(value){ // function to add value one by one to the beginning of the linked list const newNode = { value:value, next:null }; newNode.next = this.head; // newNode's reference value will now point to the head this.head = newNode; // head value will be updated with the value of new node this.length++; return this } printList(){ const array = []; let currentNode = this.head; while (currentNode !== null){ array.push(currentNode.value); currentNode = currentNode.next; } console.log(array) } insert(index,value){ //function to insert a value at a partiular index // check params if (index >= this.length){ return this.append(value); } const newNode = { value:value, next:null }; const leader = this.traverseToIndex(index-1) // leader is at the index just before which index we want to insert a new node const holdingPointer = leader.next; // we save the reference of the next node originally beside the leader , in temporary variable leader.next = newNode; newNode.next = holdingPointer; this.length++; return this.printList() } traverseToIndex(index){ //check params let counter = 0; let currentNode = this.head; while (counter !== index){ currentNode = currentNode.next; counter++; } return currentNode; } } const myLinkedList = new LinkedList(10); myLinkedList.append(5); myLinkedList.append(16); myLinkedList.prepend(1); myLinkedList.insert(2,99); myLinkedList.printList(); myLinkedList.insert(200,88); myLinkedList.printList(); console.log(myLinkedList)
Editor Settings
Theme
Key bindings
Full width
Lines