← All coursesDSA Foundations

Lesson 4 of 19

Linked lists

A scavenger hunt sends you from clue to clue. Each node stores a value and a link to the next node. Start at the head and follow the links.

A link can change the order without moving the nodes

In a singly linked list, each node knows only its successor. Finding a position can take a walk from the head. Once you hold the preceding node, inserting after it takes two link assignments, regardless of the length of the list.

Work through an example

You hold node A in A → C. How can you insert B after A and still reach C from the head?

Step-by-step solution
  1. Read A’s current next link. That link is your route to C.
  2. Give B that link first, then redirect A’s next link to B.
  3. Follow the links from A. You visit A, B and C. The same two assignments work at the tail, where the old next link is null.
JavaScript example
const a = { value: "A", next: { value: "C", next: null } };
const b = { value: "B", next: a.next };
a.next = b;
[a.value, a.next.value, a.next.next.value]; // ["A", "B", "C"]
DSA compiler

Try it yourself

Finish the animation to unlock this question.

You have only the head of A → B → C. How do you reach C?

Related exercise · Build a singly linked list · See this stage of the beginner path