Back

Linked Lists (concept)

A linked list is a chain of nodes where each node holds a value and a pointer to the next node. Adding or removing at the start is fast, but finding an item means walking the chain from the beginning.

class ListNode {
  constructor(public value: number, public next: ListNode | null = null) {}
}

// 1 -> 2 -> 3
const head = new ListNode(1, new ListNode(2, new ListNode(3)))

// Walk the list
let current: ListNode | null = head
while (current) {
  console.log(current.value)
  current = current.next
}

// Add to the front: O(1)
const newHead = new ListNode(0, head)

Roadmap