Linked List — Data Structures

A linked list is a chain of nodes. A node is a separate object that holds value and next (the address of the next node). The last node's next is null, and…

In the array lesson, inserting an item at the front made every other item move one index. A linked list stores its items another way. Take the list 10 -> 20 -> 30 (each arrow points to the next item) and add 5 at the very front: how many items have to move? The answer is none.

A linked list keeps its items in separate little boxes called nodes. Each node holds two things: its value, and the address of the next node (where that node is kept in memory). A linked list is like a treasure hunt: every clue tells you where the next clue is, so you have to follow them one by one from the first. Each clue is a node, and what it says about where to look is the address of the next node.

Node: a value and the address of the next one

This is a picture of the list 10 -> 20 -> 30. Each box is one node, with its value on the left and next on the right:

head
  |
[10 | next] --> [20 | next] --> [30 | next] --> null

This is code that builds the same list:

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

const a = new Node(10);
const b = new Node(20);
const c = new Node(30);
a.next = b;
b.next = c;

const head = a;
console.log(head.value);           // 10
console.log(head.next.value);      // 20
console.log(head.next.next.value); // 30
console.log(c.next);               // null

The LinkedList class

The LinkedList class keeps head and size (the number of nodes), with three methods: prepend, append and print (returns the list as text).

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

  prepend(value) {
    const node = new Node(value);
    node.next = this.head;
    this.head = node;
    this.size++;
  }

  append(value) {
    const node = new Node(value);
    if (this.head === null) {
      this.head = node;
    } else {
      let current = this.head;
      while (current.next !== null) {
        current = current.next;
      }
      current.next = node;
    }
    this.size++;
  }

  print() {
    let text = "head";
    let current = this.head;
    while (current !== null) {
      text += " -> " + current.value;
      current = current.next;
    }
    return text + " -> null";
  }
}

const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.prepend(5);
console.log(list.print()); // head -> 5 -> 10 -> 20 -> 30 -> null
console.log(list.size);    // 4

A new list (new LinkedList()) is empty: head is null and size is 0. Inside a method, this means the list itself. Every time a node is added, at the front or at the back, this.size++ adds one to size. The Node class from the previous section is still used.

prepend: add at the front

These are the steps of list.prepend(5) on the list 10 -> 20 -> 30:

Step Code What the list looks like
1 const node = new Node(5) node 5 on its own, its next is null
2 node.next = this.head 5 points at 10, the old list is linked behind it
3 this.head = node head -> 5 -> 10 -> 20 -> 30 -> null

No node is moved, only two pointers change. So prepend is O(1): it takes the same number of steps, however long the list is.

The order of steps 2 and 3 matters. Before step 3, head is the only place where the address of node 10 is kept. If head changes first, the address of node 10 is lost, and the rest of the list is lost with it.

append: add at the back

The list only keeps the address of the first node (head). So append first has to walk from node to node until it reaches the last node. The variable current holds the node it is visiting. These are the steps of list.append(40) on the list 10 -> 20 -> 30:

Step current is at current.next Then
1 10 20 not null, move forward
2 20 30 not null, move forward
3 30 null stop, current.next = node

The result is 10 -> 20 -> 30 -> 40 -> null. If the list is still empty, the new node simply becomes head. The longer the list, the farther append has to walk: O(n), where n is the number of nodes.

Walking from head to null

Code that reads the whole list uses the same pattern, like print() above:

  1. Start with let current = this.head.
  2. While current !== null, use current.value, then move forward with current = current.next.
  3. When current becomes null, the list has ended and the loop stops.

Want every value in an array? The pattern is the same, only the inside of the loop changes: set up an empty array [], push(current.value) on every pass, then return the array after the loop. In the exercise, you write a toArray() method with this pattern.

Linked list or array?

Array Linked list
Get the i-th item directly, O(1) walk from head, O(n)
Add at the front every item shifts, O(n) change two pointers, O(1)
Add at the back O(1) O(n), unless it keeps a tail

A linked list's main strength: adding and removing at the front only changes pointers, without moving the other items. Its weakness: it can't jump directly to the i-th item (the item at position i). The tail is explained in the 💡 note below.

⚠️ Broken links and loops that never stop

💡 A tail pointer. A list can also keep tail, the address of the last node. With tail, append doesn't need to walk: just this.tail.next = node, then this.tail = node. Append becomes O(1). Removing the last node still means walking from head, though, because you need the node before it, and next only points to the node after.

TL;DR: A linked list is a chain of nodes. A node is a separate object that holds value and next (the address of the next node). The last node's next is null, and head points at the first node. prepend adds at the front: make a new node, link it with node.next = this.head, then set this.head = node (this is the list itself). Nothing moves, so it's O(1). append adds at the back: it walks from head to the node whose next is null, then links the new node there, so it's O(n). To read the whole list, the variable current starts at head and moves with current = current.next until null. Don't forget size++ (one more node) on every add.

⚡ Node: a value and the address of the next one

Write:

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

Meaning: A linked list keeps its items in separate nodes. The Node class is a blueprint for one node: new Node(10) runs constructor and makes the object { value: 10, next: null } (this means the object being made). value is the value, and next the address of the next node. head points at the first node, and the last node's next stays null, the sign the list has ended.

⚡ prepend: add at the front

Write:

prepend(value) {
  const node = new Node(value);
  node.next = this.head;
  this.head = node;
  this.size++;
}
Guess first: you add 5 at the front of the list 10 -> 20 -> 30 (each arrow is a next). How many nodes are moved?

None. Only two pointers (stored addresses) change: node.next and this.head. So prepend is O(1): it takes the same number of steps, however long the list is.

Meaning: In the prepend method, this means the list itself, and this.size++ adds one to the node count. The order matters: link node.next first, then change head. If head changes first, the address of the old first node is lost, and the rest of the list is lost with it.

⚡ append, and walking to null

Meaning: The list only keeps head. So append first has to walk from node to node until it reaches the last node (whose next is null), then it links the new node there: O(n). Reading the whole list works the same way: the variable current starts at head, then moves with current = current.next until null.

⚡ Linked list or array?

Meaning: A linked list is good at adding and removing at the front: only pointers (the addresses in next and head) change, without moving the other items. Its weakness: it can't jump directly to the i-th item (the item at position i).

What you will learn