edubun
English
1 / 18

4 / 7 · Intermediate

Linked lists

Adding a value at the front of a linked list changes two pointers, whether the list holds 4 values or 4 million.

Jump to the 10 practice questions

You will learn

  • Build a list from nodes and next pointers
  • Count visits and pointer changes
  • Choose between an array and a linked list

Before this: Queues

1Explain

Nodes and pointers

An array keeps its values side by side, which is why the front is expensive to change. A linked list drops that rule. Each value lives in its own small record called a node, and the nodes can sit anywhere in memory. MIT's 6.006 notes describe a node with two fields: the item, and next, a pointer to the following node. The list itself only remembers the first node, called the head. The last node's next is null, which marks the end.

// one node per value: { value, next }
let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
// walk the list
for (let n = head; n !== null; n = n.next) console.log(n.value); // 12, 7, 30, 4
Output
12
7
30
4

2Problem

The two fields

What two fields does a node of a singly linked list hold?

Hint

One holds the value, one points onward.

Solution

Answer: item and next

MIT's notes: node.item and node.next, a pointer to the following node.

3Explore

Walking the list

To read the list you start at head and follow next pointers one by one, like following a chain of notes that each say where the next note is hidden. That has a cost. There is no formula for the address of the fourth node, so getting the value at position i means visiting i + 1 nodes. MIT lists get at(i) for a linked list as O(n), where the array managed it in one step.

find starts at head and follows next. The cost is the number of nodes visited.

Press a button: each one runs one operation and shows what it cost.

[12,7,30,4]

Total steps 0

4Problem

Searching for 30

Same list: how many nodes does a search for 30 visit?

Hint

12, 7, then 30.

Solution

Answer: 3

12, 7, then 30: found on the third visit.

5Problem

Searching for 99

Same list: how many nodes does a search for 99 visit before it reaches null?

Hint

A missing value means every node.

Solution

Answer: 4

A missing value means visiting every node: all 4.

6Explore

Changing the front

The payoff comes when you change the list. To put a new value at the front, make a node whose next is the current head, then point head at the new node. Two pointer changes, and nothing else moves. Deleting the front node is one change: point head at head.next. Compare that with the array, where the same operations moved every value.

A new front node costs 2 pointer changes; removing the front costs 1. Nothing else moves, however long the list.

Press a button: each one runs one operation and shows what it cost.

[12,7,30,4]

Total steps 0

7Problem

Insert at the front

List 12 → 7 → 30 → 4. How many steps does inserting a new value at the front take (pointer changes)?

Hint

new.next = head, then head = new.

Solution

Answer: 2

new.next = head, then head = new. No node is visited and nothing moves.

8Problem

The array, for comparison

An array holds 1,000 values with room to spare. How many steps does inserting at the front take?

Hint

1,000 moves and 1 write.

Solution

Answer: 1001

1,000 moves + 1 write = 1,001, against 2 pointer changes for a linked list.

9Explain

Inserting in the middle

In the middle, the work is finding the spot. To insert at position i you walk to the node just before it (i visits), then do the same two pointer changes: new.next = prev.next, then prev.next = new. The order matters. If you set prev.next first, the rest of the list is lost, because nothing points to it any more. In the lab a step is one node visited or one pointer changed, so inserting at position 2 of a 4-node list costs 2 visits plus 2 changes, 4 steps.

First the new node points at the rest of the list, then prev points at the new node. The other order would lose the rest.

  1. let head = { value: 12, next: { value: 7, next: { value: 30, next: null } } };
  2. const prev = head.next;
  3. const node = { value: 99, next: null };
  4. node.next = prev.next;
  5. prev.next = node;
  6. console.log(head.next.next.value);
Variables
Output
99

10Problem

The safe order

When inserting after node p, which order of steps keeps the rest of the list?

Hint

Which pointer is the only way to reach the rest?

Solution

Answer: new.next = p.next, then p.next = new

Setting p.next first would lose the only pointer to the rest of the list.

11Problem

Insert at position 2

Same list: inserting at position 2 costs how many steps (visits plus pointer changes)?

Hint

2 visits, 2 changes.

Solution

Answer: 4

Visit nodes 0 and 1 to reach the node before position 2, then 2 pointer changes: 2 + 2 = 4.

12Problem

Delete at position 3

Same list: deleting the node at position 3 (the 4) costs how many steps?

Hint

3 visits to reach the node before it, then 1 change.

Solution

Answer: 4

Visit nodes 0, 1, 2 to reach the one before it (3 visits), then change 1 pointer: 4.

13Explain

Array or linked list

A linked list is a good fit when most changes happen at a place you already hold a pointer to, such as the front, and you rarely need position i. Queues and stacks can be built from linked lists, and so can the chains inside a hash table in the next unit.

OperationArray (n values)Linked list (n nodes)
Get the value at position i1i + 1 visits
Insert at the frontn moves + 1 write2 pointer changes
Delete the front1 read + (n − 1) moves1 pointer change
Insert at position i(n − i) moves + 1 writei visits + 2 changes
Find a valueup to n readsup to n visits

14Problem

A job for a linked list

Which job suits a linked list better than an array?

Hint

Which changes happen at the front?

Solution

Answer: Adding and removing at the front many times

Front changes are 1 or 2 pointer changes; position 500 would mean 501 visits each time.

15Practice

Write a list walker

Walk the list and collect its values. It should print 12 7 30 4 (each new node went in at the front).

Expected output
12 7 30 4
Your code
let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
function toArray(head) {
  const out = [];
  // Start at head and follow next until you reach null,
  // pushing each node's value into out.
  return out;
}
console.log(toArray(head).join(" "));
Hint

Stop when n itself is null, not when n.next is null, or the last node is skipped.

A solution
let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
function toArray(head) {
  const out = [];
  for (let n = head; n !== null; n = n.next) out.push(n.value);
  return out;
}
console.log(toArray(head).join(" "));

16Practice

Relink the pointers

Finish both functions by relinking pointers. It should print 12 7 99 30 4 and then 12 99 30 4.

Expected output
12 7 99 30 4
12 99 30 4
Your code
function list(...vals) { let h = null; for (let i = vals.length - 1; i >= 0; i--) h = { value: vals[i], next: h }; return h; }
const show = (h) => { const out = []; for (let n = h; n !== null; n = n.next) out.push(n.value); return out.join(" "); };
let head = list(12, 7, 30, 4);
function insertAfter(node, v) {
  // Make a node whose next is node.next, then point node.next at it.
}
function deleteAfter(node) {
  // Point node.next past the node that follows.
}
insertAfter(head.next, 99);
console.log(show(head));
deleteAfter(head);
console.log(show(head));
Hint

The new node must point at what node.next pointed at before.

A solution
function list(...vals) { let h = null; for (let i = vals.length - 1; i >= 0; i--) h = { value: vals[i], next: h }; return h; }
const show = (h) => { const out = []; for (let n = h; n !== null; n = n.next) out.push(n.value); return out.join(" "); };
let head = list(12, 7, 30, 4);
function insertAfter(node, v) {
  node.next = { value: v, next: node.next };
}
function deleteAfter(node) {
  node.next = node.next.next;
}
insertAfter(head.next, 99);
console.log(show(head));
deleteAfter(head);
console.log(show(head));

17Explain

Common mistakes

let head = { value: 12, next: null };
let n = head;
while (true) {
  console.log(n.value);
  n = n.next;
}
Error message
12
TypeError: Cannot read properties of null (reading 'value') (line 4)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. The line number shows where the program stopped. A SyntaxError stops it before any line runs.

The loop never checks for the end, so it reads .value from null. Loop while n !== null.

18

Summary

  • A linked list stores each value in a node with a next pointer; the list keeps head.
  • Insert or delete at the front changes 1 or 2 pointers; nothing moves.
  • Reaching position i takes i + 1 visits, so get at(i) is O(n).
  • Set new.next before relinking the previous node.

Next unitHash tables
Full text · The whole lesson as one text

Values that point to the next one

An array keeps its values side by side, which is why the front is expensive to change. A linked list drops that rule. Each value lives in its own small record called a node, and the nodes can sit anywhere in memory. MIT's 6.006 notes describe a node with two fields: the item, and next, a pointer to the following node. The list itself only remembers the first node, called the head. The last node's next is null, which marks the end.

To read the list you start at head and follow next pointers one by one, like following a chain of notes that each say where the next note is hidden. That has a cost. There is no formula for the address of the fourth node, so getting the value at position i means visiting i + 1 nodes. MIT lists get at(i) for a linked list as O(n), where the array managed it in one step.

// one node per value: { value, next }
let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
// walk the list
for (let n = head; n !== null; n = n.next) console.log(n.value); // 12, 7, 30, 4

Changing the list by relinking

The payoff comes when you change the list. To put a new value at the front, make a node whose next is the current head, then point head at the new node. Two pointer changes, and nothing else moves. Deleting the front node is one change: point head at head.next. Compare that with the array, where the same operations moved every value.

In the middle, the work is finding the spot. To insert at position i you walk to the node just before it (i visits), then do the same two pointer changes: new.next = prev.next, then prev.next = new. The order matters. If you set prev.next first, the rest of the list is lost, because nothing points to it any more. In the lab a step is one node visited or one pointer changed, so inserting at position 2 of a 4-node list costs 2 visits plus 2 changes, 4 steps.

A singly linked list of four nodes. Choose a position with the slider and insert or delete; the counter separates nodes visited from pointers changed. Find walks from head until it meets the value or null.
OperationArray (n values)Linked list (n nodes)
Get the value at position i1i + 1 visits
Insert at the frontn moves + 1 write2 pointer changes
Delete the front1 read + (n − 1) moves1 pointer change
Insert at position i(n − i) moves + 1 writei visits + 2 changes
Find a valueup to n readsup to n visits

When to use one

A linked list is a good fit when most changes happen at a place you already hold a pointer to, such as the front, and you rarely need position i. Queues and stacks can be built from linked lists, and so can the chains inside a hash table in the next unit. There are variants. A doubly linked list gives each node a prev pointer too, so you can walk backwards and delete a node in one step once you have it. Keeping a tail pointer as well as head makes adding at the end cheap.

In everyday JavaScript you rarely write a linked list, because arrays are well optimized and caches in modern processors favour values stored side by side. The idea matters anyway: trees, graphs and many library structures are built from nodes and pointers in exactly this way.

BackgroundLinked lists appeared in the mid-1950s with the Information Processing Language (IPL), written by Allen Newell, Cliff Shaw and Herbert Simon at the RAND Corporation and the Carnegie Institute of Technology around 1956. Their programs searched for proofs of logic theorems, and the number and size of the things they had to remember could not be known in advance. Lists of linked cells let memory be handed out and taken back one cell at a time. IPL's list processing influenced Lisp, which John McCarthy designed a few years later.
Key points
  • A linked list stores each value in a node with a next pointer; the list keeps head.
  • Insert or delete at the front changes 1 or 2 pointers; nothing moves.
  • Reaching position i takes i + 1 visits, so get at(i) is O(n).
  • Set new.next before relinking the previous node.

Practice questions from Linked lists on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append)
  • 4 Hashing (chaining, pigeonhole collisions, chain length n/m)
  • 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1)
  • Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262)
  • 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements")
  • Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18