DoublyLinkedList

Run Settings
LanguageJavaScript
Language Version
Run Command
class Node{ constructor(value) { this.data = value; this.next = null; this.prev = null; } } class DoublyLinkedList{ constructor(value){ this.head = new Node(value); this.tail = this.head; this.length = 1; } append(value){ let newNode = new Node(value); this.tail.next = newNode; newNode.prev = this.tail; this.tail = newNode; this.length++; } prepend(value) { let newNode = new Node(value); newNode.next = this.head; this.head.prev = newNode; this.head = newNode; this.length++; } printList(){ let arr = []; let currNode = this.head; while(currNode!=null) { arr.push(currNode.data); currNode = currNode.next; } return arr; } insertAt(n,value) { if(n>=this.length) return this.append(value); let count = 0; let currNode = this.head; while(count!=n) { currNode = currNode.next; count++; } let newNode = new Node(value); newNode.next = currNode.next; currentNode.next.prev = newNode; newNode.prev = currNode; currNode.next = newNode; this.length++; } remove(n) { if(n>=this.length) return -1; let count = 0; let currNode = this.head; let prev = this.head; while(count!=n) { prev = currNode; currNode = currNode.next; count++; } prev.next = currNode.next; currNode.next.prev = prev; currNode=null; return true; } reverse() { let first = this.head; this.tail = this.head; let second = first.next; while(second) { let temp = second.next; second.next = first; first.prev = second; first = second; second = temp; } this.head.next = null; this.head = first; } } let obj = new DoublyLinkedList(6); obj.append(5); obj.append(7); obj.prepend(1); obj.insertAt(100,100); // obj.remove(2); obj.reverse() console.log(obj.printList())
Editor Settings
Theme
Key bindings
Full width
Lines