Implementation of Linked List

Run Settings
LanguageJavaScript
Language Version
Run Command
class LinkedList{ constructor(value){ this.head={ value:value, next:null, } this.tail=this.head this.length=1 } append(value){ const newNode={ value:value, next:null }; this.tail.next=newNode; this.tail=newNode; this.length++; return this; } prepend(value){ const newNode={ value:value, next:null, }; newNode.next=this.head; this.head=newNode; this.length++; return this; } printList(){ const array=[] let currentNode=this.head; while(currentNode!==null){ array.push(currentNode.value); currentNode=currentNode.next; } console.log(array) return array; } insert(index,value){ if(index>=this.length){ return this.append(value) } if(index===0){ return this.prepend(value) } const newNode={ value:value, next:null, }; const leader=this.traverseIndex(index-1) const holdingPointer=leader.next; leader.next=newNode; newNode.next=holdingPointer; this.length++; return this.printList } traverseIndex(index){ let counter=0; let currentNode=this.head; while(counter!=index){ currentNode=currentNode.next; counter++; } return currentNode } remove(index){ const leader=this.traverseIndex(index-1); const unWantedNode=leader.next; leader.next=unWantedNode.next; this.length--; return this.printList() } } const myLinkedList=new LinkedList(10) myLinkedList.append(3) myLinkedList.append(16) myLinkedList.prepend(4) myLinkedList.prepend(69) myLinkedList.insert(1,45) myLinkedList.insert(1,23) myLinkedList.remove(2) myLinkedList.remove(2) myLinkedList.remove(0)
Editor Settings
Theme
Key bindings
Full width
Lines