Intermediate 15 min

Singly linked lists

Follow a chain of nodes and understand which updates are cheap when you have the right reference.

Store the next reference

A singly linked list is a chain. Each node holds a value and a reference to the next node, with an empty reference after the last value. The head reference names the first node. To read a specific position, follow references from the head until reaching it.

How it works

Draw one node per box and its next field as an arrow. Inserting B between A and C means making B point to C and then making A point to B. Preserving the C arrow matters so the rest of the list stays reachable.

Insert by rewiring one link

To insert after a known node, point the new node at the old next node before making the known node point at the new one. This takes O(1) time when you already have the node. Finding the node first can take O(n) time.

Code example

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node

head = Node("A", Node("C"))
head.next = Node("B", head.next)
node = head
while node is not None:
    print(node.value)
    node = node.next

Check your understanding

Insert B after A and report the resulting node order.

See the example and explanation
Example 1
Given A → C
Answer A → B → C
Example 2
Given A
Answer A → B

Set B’s next reference first, then update A’s. If A pointed to C, the result has all three nodes. If A was last, the new final node B points to no next node.

Open practice problem
Next lessonHash maps and counting