DSAintermediate 9 min
Nodes that point to each other. Cheap inserts, but no jumping to an index.
How a linked list is built from nodes, and how it trades fast insertion for slow lookup compared to an array.
Linked lists teach you to think in references (pointers). They also power queues, undo chains and the history of many data structures.
A linked list is a chain of nodes. Each node holds a value and a link to the next node. The first node is called the head. The last node points to null.
Because nodes are not side by side in memory, you cannot jump to "item 5". You must walk from the head, one link at a time: O(n) to find something.
The upside: adding or removing at the head is O(1). You only change a link, and nothing needs to shift.
A linked list: each node points to the next one.
1 -> 2 -> 3, where head is the node holding 1.prepend 0 makes a new node that points at the old head, then moves head to it. No shifting.append 4 has to walk to the end first.find and delete walk one node at a time until they reach the target.0 -> 1 -> 2 -> 3.Add a function that returns the length of the list by walking it.
head without saving it, the rest of the list is gone.cur !== null.Next: sorting.
class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
// build 1 -> 2 -> 3
let head = new Node(1, new Node(2, new Node(3)));
// prepend 0: O(1)
head = new Node(0, head);
// walk the list: O(n)
let cur = head;
const out = [];
while (cur !== null) {
out.push(cur.value);
cur = cur.next;
}
console.log(out.join(" -> "));