Doubly Linked List — Data Structures

In a doubly linked list, every node has next (the address of the node after it) and prev (the address of the node before it). The list keeps head (the first…

The linked list from the last lesson can only be walked in one direction. Want to remove the last node? You have to walk from head to the node before the last one, because each node only keeps the address of the node after it.

A doubly linked list fixes that problem: every node has two pointers, next to the node after it and prev to the node before it. The list also keeps both ends: head (the first node) and tail (the last node). Think of the carriages of a train: each one is joined to the carriage in front and the one behind, so you can walk in both directions. Each carriage is a node, and the joins on its two sides are prev and next.

Nodes with prev and next

This is a picture of the list A, B, C:

        head                        tail
         |                           |
null <- [A] <-------> [B] <-------> [C] -> null

This is code that builds the same list:

class DNode {
  constructor(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

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

  append(value) {
    const node = new DNode(value);
    if (this.tail === null) {
      this.head = node;
      this.tail = node;
    } else {
      node.prev = this.tail;
      this.tail.next = node;
      this.tail = node;
    }
    this.size++;
  }
}

const list = new DoublyLinkedList();
list.append("A");
list.append("B");
list.append("C");

console.log(list.head.value);      // A
console.log(list.tail.value);      // C
console.log(list.head.next.value); // B
console.log(list.tail.prev.value); // B
console.log(list.size);            // 3

These are the steps of list.append("C") on the list A <-> B (an arrow both ways means next and prev):

Step Code What changes
1 const node = new DNode("C") C on its own
2 node.prev = this.tail C points back at B
3 this.tail.next = node B points forward at C
4 this.tail = node tail is now C

Every new link needs two pointers: one forward (next) and one back (prev). Append here is still O(1).

prepend: the mirror of append

Adding at the front uses the same steps, but head takes the place of tail, and prev and next swap places. This table puts the two side by side:

append (at the back) prepend (at the front)
node.prev = this.tail node.next = this.head
this.tail.next = node this.head.prev = node
this.tail = node this.head = node

The empty-list rule applies to prepend too: the first node that comes in becomes both head and tail. Both methods also have this.size++.

Walking forward and walking back

To walk forward: start at head, follow next. To walk back: start at tail, follow prev. This code walks back through the list A, B, C from the section above:

let current = list.tail;
while (current !== null) {
  console.log(current.value);
  current = current.prev;
}
// C
// B
// A

In the exercise, you write toArrayForward() (forward) and toArrayBackward() (back): set up [], push(current.value) on every pass, then return the array after the loop.

Removing at the back

The node before the last one is already kept in tail.prev. So removeLast doesn't need to walk from head. The steps:

  1. Move tail to tail.prev.
  2. Set the new tail's next to null.

If the node you remove is the only one, tail.prev is null, and step 2 stops with TypeError: Cannot set properties of null (setting 'next'): in that case, set head and tail to null. No node is walked past, so it's O(1). Removing a node in the middle is easy too: link the nodes before and after it to each other. Both can be reached from the node you remove, through prev and next.

Singly or doubly?

Singly linked list Doubly linked list
Pointers per node 1 (next) 2 (prev and next)
Directions forward only forward and back
Remove the last node walk from head, O(n) through tail.prev, O(1)

The price of these strengths is memory: every node stores one extra pointer. The value in the node itself isn't stored twice. A doubly linked list is used when you need to walk forward and back, like the back and forward buttons in a browser, the previous and next song in a playlist, or an LRU cache (temporary storage that throws away the data not used for the longest time).

⚠️ Why does walking backwards break?

TL;DR: In a doubly linked list, every node has next (the address of the node after it) and prev (the address of the node before it). The list keeps head (the first node) and tail (the last node). append (add at the back): node.prev = this.tail, this.tail.next = node, this.tail = node (this is the list itself). prepend (add at the front) uses the same steps through head, with prev and next swapped. If the list is empty, the first node becomes both head and tail. Walking forward goes from head through next, walking back from tail through prev. Adding and removing at either end is O(1), and the price is one extra pointer in every node.

⚡ Two pointers in every node

Write:

class DNode {
  constructor(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

Meaning: In a doubly linked list, every node has two pointers: next to the node after it and prev to the node before it. The DNode class is a blueprint for one node: constructor runs when a node is made, and prev and next start as null (this means that node). The list keeps both ends: head (the first node) and tail (the last node).

⚡ Every link needs two pointers

Write:

node.prev = this.tail;
this.tail.next = node;
this.tail = node;
Guess first: if you forget node.prev = this.tail, what breaks?

Walking forward (through next) still works, but walking back (through prev) breaks, because the new node doesn't point back at the node before it.

Meaning: These three lines are the inside of append, which adds a node at the back (this means the list itself). Because it goes through tail, append doesn't walk from the front: O(1). prepend (add at the front) uses the same steps through head. If the list is still empty, the first node becomes both head and tail.

⚡ Forward and back

Meaning: To walk forward: start at head, follow next. To walk back: start at tail, follow prev. The node before the last one is already kept in tail.prev, so removing the last node doesn't need a walk from head: O(1).

⚡ The price is memory

Guess first: why does a doubly linked list use more memory than an ordinary linked list?

Every node stores two pointers, prev and next, instead of one. The value in the node itself isn't stored twice.

Meaning: Use a doubly linked list when you need to walk forward and back, like the back and forward buttons in a browser, or an LRU cache (temporary storage that throws away the data not used for the longest time).

What you will learn