Doubly Linked Lists

The only difference between a doubly linked list and a singly linked list is that you add a pointer to the previous node as well.

This makes operations like pop much faster because you can traverse backwards.

However, as a result of this extra pointer, doubly linked lists take up more memory.

Constructors

class Node {
  constructor(val) {
    this.val = val
    this.prev = null
    this.next = null
  }
}

class DoublyLinkedList {
  constructor() {
    this.length = 0
    this.head = null
    this.tail = null
  }
}

Operations

Push

Pop

Unshift

Shift

Get

The only thing special about get is that because you can traverse forwards or backwards, you can conditionally traverse in either direction depending on if the index is closer to the left or closer to the right. This is a slight optimization that makes get O(n / 2).

Set

Insert

With insert, the only special thing you're doing is connecting nodes at both ends (prev and next).

Remove

Just like insert, remove requires connecting the severed ends of each surrounding node.

Reverse

Big O

Insertion and removal are always O(1) because next and prev make it easy to find the nearby node.

Search and access is still O(n) because you're still traversing the length of the list.

However: As mentioned before, the extra prev pointer means more space complexity.

Last updated