DoublyLinkedList

Run Settings
LanguageJavaScript
Language Version
Run Command
class Node { constructor(value) { this.value = value; this.prev = null; this.next = null; } } class LinkedList { constructor(value) { this.head = new Node(value); this.tail = this.head; this.length = 1; } printList() { const array = []; let currentNode = this.head; while( currentNode !== null ) { array.push(currentNode.value); currentNode = currentNode.next; } return array; } prepend(value) { const newNode = new Node(value); newNode.next = this.head; this.head.prev = newNode; this.head = newNode; this.length++; } append(value) { const newNode = new Node(value); this.tail.next = newNode; newNode.prev = this.tail; this.tail = newNode; this.length++; } insert(value, index) { if(index >= this.length) { return this.append(value); } const newNode = new Node(value); let leader = this._traverseToIndex(index - 1); let follower = leader.next; leader.next = newNode; newNode.prev = leader; newNode.next = follower; follower.prev = newNode; this.length++; } remove(index) { if( index >= this.length || index < 0) { return 'out of bounds index'; } if( index === 0 ) { this.head = this.head.next; } else { let leader = this._traverseToIndex(index -1); let unwantedNode = leader.next; if ( unwantedNode ) { unwantedNode.next.prev = leader; } leader.next = unwantedNode.next; } this.length--; } _traverseToIndex(index){ let counter = 0; let currentNode = this.head; while( counter < index ) { currentNode = currentNode.next; counter++; } return currentNode; } } const linkedList = new LinkedList(5); linkedList.prepend(4) linkedList.append(8); linkedList.insert(6,3) linkedList.remove(1); console.log(linkedList.printList()); console.log(linkedList);
Editor Settings
Theme
Key bindings
Full width
Lines