MyDoubleLinkedList

Run Settings
LanguageJavaScript
Language Version
Run Command
class MyDoubleLinkedList { constructor(value) { this.head = { value, next: null, previous: null } this.tail = this.head; this.length = 1; } newNode(value) { return { value, next: null, previous: null }; } append(value) { const node = this.newNode(value); if(this.tail === null) { this.tail = node; this.head = this.tail; }else { this.tail.next = node; node.previous = this.tail; this.tail = node; } this.length++; } prepend(value) { const node = this.newNode(value); if(this.head === null) { this.head = node; this.tail = this.head; }else { node.next = this.head; this.head.previous = node; this.head = node; } this.length++; } insertNode(value, index) { if(index >= this.length) { this.append(value); }else if(index <= 0) { this.prepend(value); }else { const node = this.newNode(value); const prevNode = this.traversal(index-1); const nextNode = prevNode.next; prevNode.next = node; nextNode.previous = node; node.previous = prevNode; node.next = nextNode; this.length++; } } deleteNode(index) { if(this.length === 0 || index < 0 || index >= this.length) { return false; }else { if(index === 0) { if(this.length === 1) { this.head = null; this.tail = null; this.length = 0; }else { const removedNode = this.head; this.head = this.head.next; this.head.previous = null; removedNode.next = null; this.length--; } }else { const prevNode = this.traversal(index-1); const nextNode = prevNode.next; prevNode.next = nextNode.next; nextNode.next = null; nextNode.previous = null; this.length--; if(nextNode === this.tail) { this.tail = prevNode; }else { prevNode.next.previous = prevNode; } } return true; } } traversal(index) { // Need to change based on index value // If index is less than half of the length then start from 0 otherwise start from end let current = this.head; for(let i=0;i < index && current !== null;i++) { current = current.next; } return current; } } const firstLinkedList = new MyDoubleLinkedList(10); firstLinkedList.append(5); firstLinkedList.append(16); firstLinkedList.prepend(1); console.log(firstLinkedList.deleteNode(1)); firstLinkedList.insertNode(3, 1); console.log(firstLinkedList);
Editor Settings
Theme
Key bindings
Full width
Lines