Doubly Linked List
class Node {
constructor(value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.length = 0;
this.head = null;
this.tail = null;
}
// Add node to the start of the list
insertHead(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.head.prev = newNode;
newNode.next = this.head;
this.head = newNode;
}
this.length++;
return newNode;
}
// Add node to the end of the list
insertTail(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return newNode;
}
// Remove node at the start of the list.
removeHead() {
if (this.length === 0) {
return null;
}
const nodeToRemove = this.head;
if (this.length === 1) {
this.head = null;
this.tail = null;
} else {
this.head = nodeToRemove.next;
this.head.prev = null;
nodeToRemove.next = null;
}
this.length--;
return nodeToRemove.value;
}
// Remove node at the end of the list.
removeTail() {
if (this.length === 0) {
return null;
}
const nodeToRemove = this.tail;
if (this.length === 1) {
this.head = null;
this.tail = null;
} else {
this.tail = nodeToRemove.prev;
this.tail.next = null;
nodeToRemove.prev = null;
}
this.length--;
return nodeToRemove.value;
}
getHead() {
return this.head ? this.head.value : null;
}
getTail() {
return this.tail ? this.tail.value : null;
}
size() {
return this.length;
}
// Return list values
toString() {
const list = [];
let currentNode = this.head;
while (currentNode !== null) {
list.push(JSON.stringify(currentNode.value));
currentNode = currentNode.next;
}
return list.toString();
}
}
const dll = new DoublyLinkedList();
Operation
Time Complexity
insertHead
O(1)
insertTail
O(1)
removeHead
O(1)
removeTail
O(1)
getHead
O(1)
getTail
O(1)
size
O(1)
toString
O(n)
Last updated
Was this helpful?