Linked List - Class based Singly Linked List

Run Settings
LanguageJavaScript
Language Version
Run Command
class LinkedList{ constructor(val){ this.head={ value:val, next:null }; this.tail = this.head; this.length = 1 } append(val){ this.tail.next={ value:val, next:null } this.tail = this.tail.next; this.length++; } prepend(val){ let currentHead = this.head; this.head={ value:val, next : currentHead } this.length++; } printList(){ const array=[]; let currentNode=this.head; while(currentNode){ array.push(currentNode.value); currentNode = currentNode.next; } return array; } remove(index){ if (this.length===0){ console.log("Create a linked list first!!!"); return; } if(index >= this.length){ console.log("Specify an index that is less than the length of the Linked List!!!"); return; } if (index ===0){ this.head = this.head.next; return; } let currNode = this.head; let prevNode = null; for(let i=0;i<this.length;i++){ if (i===index){ prevNode.next = currNode.next; } prevNode=currNode; currNode=currNode.next; } this.length--; } insert(index,val){ if (this.length===0){ console.log("Create a linked list first!!!"); return; } if(index >= this.length){ console.log("Specify an index that is less than the length of the Linked List!!!"); return; } if (index ===0){ this.prepend(val); }else if (index==this.length-1){ this.append(val); }else{ let nextNode = this.head; for(let i=0;i<this.length;i++){ if (i===index-1){ let futureNode = nextNode.next; nextNode.next={ value:val, next : futureNode } } nextNode=nextNode.next; } this.length++; } } reverse(){ if (this.length === 1){ return this.head; } let first = this.head; this.tail = this.head; let second = first.next; while(second){ const temp = second.next; second.next = first; first = second; second=temp; } this.head.next = null; this.head=first; } } const myLinkedList = new LinkedList(1); //console.log(myLinkedList); myLinkedList.append(10); //console.log(myLinkedList); myLinkedList.append(16); //console.log(myLinkedList); myLinkedList.append(88); //console.log(myLinkedList); console.log(myLinkedList.printList()); //myLinkedList.insert(3,99); //console.log(myLinkedList); //console.log(myLinkedList.printList()); //myLinkedList.remove(0); myLinkedList.reverse(); console.log(myLinkedList.printList());
Editor Settings
Theme
Key bindings
Full width
Lines