AlgoViz

Singly linked list

easy 18 min

A singly linked list is a chain of nodes where each node holds a value and a pointer to the next node.

Video lesson · Chapter 1 of 6

Follow the couplers

0:00 / 4:26

Singly linked lists — Rook’s mail route

1:25Reel

Read caption

Rook follows mail tags from dock 8 to 3 to 11, then splices dock 6 into the route. Find by following. Insert by redirecting.

How it works

Step through the idea, or press Play.

Step 1 of 3

Hold the head. The head pointer is your only way in; lose it and the whole list is gone

Understand it

Start here

What a singly linked list is

A singly linked list is a linear data structure made of nodes. Each node stores a value and a pointer called next to the node after it. The nodes are not side by side in memory; the pointers are the only thing holding the chain together. A special pointer, the head, marks the first node, and the last node's next is None (NULL).

  • Nodes, not slots

    Each node is a small object: a value plus one next pointer.

  • One way only

    You can walk forward from the head. There is no way back to the previous node.

  • Grows one node at a time

    No capacity, no resizing. Create a node and link it in.

Anatomy

Nodes, head and NULL

Anatomy of the chain

The head points at the first node. Each next points at the following node, and the last one points at NULL.
PartWhat it holdsWhy it matters
valThe dataWhat you store and search for
nextA reference to the next node, or NoneThe only link to the rest of the list
headA reference to the first nodeLose it and every node becomes unreachable
NULL (None)The end markerEvery loop stops when current becomes None
Python
class Node:    def __init__(self, val, next=None):        self.val = val        self.next = next# build 10 -> 20 -> 30 -> None by handhead = Node(10, Node(20, Node(30)))print(head.val, head.next.val, head.next.next.val)   # 10 20 30print(head.next.next.next)                           # None
A node is two fields. A list is just a reference to the first node.
Edit and run it in your browser

Memory

Scattered nodes versus a contiguous array

An array keeps its elements in one block, so the computer can calculate where element ii lives. A linked list's nodes can be anywhere on the heap, so the only way to find node kk is to follow kk pointers from the head.

Calculate versus follow

array: addr⁡(i)=base+i⋅s  ⇒  O(1)list: head→next→⋯→next⏟k hops  ⇒  O(k)\text{array: } \operatorname{addr}(i) = \text{base} + i \cdot s \;\Rightarrow\; O(1) \qquad \text{list: } \underbrace{\text{head} \to \text{next} \to \dots \to \text{next}}_{k \text{ hops}} \;\Rightarrow\; O(k)
ss is the size of one element. One multiplication finds any array slot; a list needs kk pointer hops to reach index kk, and n−1n - 1 hops to reach the tail.

The price of the pointer

memory=n (d+p)vsn de.g. d=8,  p=8  ⇒  2×\text{memory} = n\,(d + p) \quad\text{vs}\quad n\,d \qquad \text{e.g. } d = 8,\; p = 8 \;\Rightarrow\; 2\times
Each node stores its data (dd bytes) plus a pointer (pp bytes, 8 on a 64-bit machine). In Python each node is a full object, so the real overhead is larger still.

Insert

Inserting at the head, the tail or a position

WherePointer changesCostOn 10 → 20 → 30
Headnew.next = head, then head = newO(1)O(1)insert 5: 5 → 10 → 20 → 30
Tailwalk to the last node, then last.next = newO(n)O(n), O(1)O(1) with a tail pointerinsert 40: 10 → 20 → 30 → 40
Position kkwalk k−1k - 1 steps, new.next = cur.next, cur.next = newO(k)O(k)insert 25 at 2: 10 → 20 → 25 → 30

insert_at(k, x)

Position 0 is special because it is the only insert that changes the head.

Delete

Deleting by bypassing a node

Deleting never erases anything. You point the previous node around the target: prev.next = target.next. Nothing references the target any more, so Python's garbage collector frees it.

delete_at(k)

Delete tail is the same move with k=n−1k = n - 1: you must find the second-to-last node, so it costs O(n)O(n) even with a tail pointer.

Cheap deletes

  • Delete head: one assignment, O(1)O(1).
  • Delete the node after one you already hold: O(1)O(1).
  • No elements shift, unlike an array.

Expensive deletes

  • Delete tail: walk to the second-to-last node, O(n)O(n).
  • Delete by value or by position: walk to find it first, O(n)O(n).
  • You need the node before the target, which a singly list cannot step back to.

Walk

Traversal and search

search(target)

Traversal is the same loop without the comparison. Every operation away from the head is built on it.

Average cost of a successful search

E[nodes checked]=1n∑i=1ni=n+12=O(n)\mathbb{E}[\text{nodes checked}] = \frac{1}{n}\sum_{i=1}^{n} i = \frac{n+1}{2} = O(n)
If the target is equally likely to be any node, you check about half the list on average, all of it when the value is missing. Halving a linear cost is still linear.
Python
class Node:    def __init__(self, val, next=None):        self.val = val        self.next = nexthead = Node(10, Node(20, Node(30, Node(40))))def to_list(head):    out, current = [], head    while current:        out.append(current.val)        current = current.next    return outdef search(head, target):    current, index = head, 0    while current:        if current.val == target:            return index        current, index = current.next, index + 1    return -1print(to_list(head))      # [10, 20, 30, 40]print(search(head, 30))   # 2print(search(head, 99))   # -1
Traverse and search share one loop shape.
Edit and run it in your browser

Complexity

What each operation costs

OperationTimeSpaceWhy
Insert at headO(1)O(1)O(1)O(1)Two pointer assignments
Insert at tailO(n)O(n)O(1)O(1)Walk to the last node; O(1)O(1) if you keep a tail pointer
Insert at position kkO(k)O(k)O(1)O(1)Walk k−1k - 1 nodes first
Delete headO(1)O(1)O(1)O(1)Move head to head.next
Delete tailO(n)O(n)O(1)O(1)Must find the second-to-last node
Search, access by indexO(n)O(n)O(1)O(1)No random access
Reverse (iterative)O(n)O(n)O(1)O(1)Visit each node once, three pointers
The list itselfO(n)O(n)One node per element, each with a pointer

Linked list wins

  • Insert at the head: O(1)O(1) versus O(n)O(n) shifting.
  • Delete at the head: O(1)O(1).
  • Never reallocates or copies when it grows.
  • Splicing two lists is a pointer change.

Array wins

  • Access by index: O(1)O(1) versus O(n)O(n).
  • Binary search on sorted data.
  • Cache-friendly, contiguous memory.
  • Less memory: no pointer per element.

Classic

Reversing a list in place

Iterative reverse

Each lap flips one arrow. When current falls off the end, prev is the old tail and the new head.

The four moves, every lap

  1. 1

    Save next

    next_node = current.next, before anything is overwritten.

  2. 2

    Reverse the link

    current.next = prev points this node backwards.

  3. 3

    Advance prev

    prev = current: the reversed part now starts here.

  4. 4

    Advance current

    current = next_node, using the saved reference.

Python
class Node:    def __init__(self, val, next=None):        self.val = val        self.next = nextdef reverse(head):    prev, current = None, head    while current:        next_node = current.next   # save next        current.next = prev        # reverse the link        prev = current             # advance prev        current = next_node        # advance current    return prev                    # the new headhead = reverse(Node(10, Node(20, Node(30, Node(40)))))out = []while head:    out.append(head.val)    head = head.nextprint(out)   # [40, 30, 20, 10]
Reverse with three pointers: O(n) time, O(1) extra space. Return the new head.
Edit and run it in your browser

Pattern

Slow and fast pointers

  • Find the middle

    Slow moves 1, fast moves 2. When fast runs out, slow is at the middle.

  • Detect a cycle

    If the list loops, fast laps slow and they meet. If not, fast hits NULL.

  • Nth from the end

    Give fast an n-node head start, then move both. When fast ends, slow is n from the end.

Why slow lands on the middle

after t laps: slow=t,  fast=2t⇒stop when 2t≥n−1  ⇒  slow=⌊n2⌋\text{after } t \text{ laps: slow} = t,\; \text{fast} = 2t \quad\Rightarrow\quad \text{stop when } 2t \ge n - 1 \;\Rightarrow\; \text{slow} = \left\lfloor \tfrac{n}{2} \right\rfloor
Indexes are 0-based. For n=5n = 5 slow stops at index 2, the true middle; for n=6n = 6 at index 3, the second of the two middle nodes.

Floyd's cycle detection

Inside a loop of length LL the gap between fast and slow shrinks by exactly one node per lap, so they meet within LL laps of slow entering it: O(n)O(n) time, O(1)O(1) space.

Toolkit

Dummy nodes and tail pointers

Most head-related bugs come from the head being special. A dummy node (also called a sentinel) is a fake node placed before the head, so every real node has a node before it and there is no special case.

Python
class Node:    def __init__(self, val, next=None):        self.val = val        self.next = nextdef remove_all(head, target):    dummy = Node(0, head)        # sits before the real head    prev = dummy    while prev.next:        if prev.next.val == target:            prev.next = prev.next.next   # bypass        else:            prev = prev.next    return dummy.next            # the real head, maybe newhead = remove_all(Node(5, Node(10, Node(5, Node(20, Node(5))))), 5)out = []while head:    out.append(head.val)    head = head.nextprint(out)   # [10, 20]
Remove every node with a given value. The dummy means deleting the head needs no extra branch.
Edit and run it in your browser
  • Dummy node

    Handles the empty list, head deletes and merges with one code path. Return dummy.next.

  • Tail pointer

    Makes append O(1)O(1), which is how a linked-list queue works. Delete tail stays O(n)O(n).

  • Size counter

    Update it on every insert and delete to answer len() in O(1)O(1) instead of walking.

Choosing

Linked list or array?

Array or linked list?

In Python, collections.deque already gives O(1)O(1) at both ends; reach for a hand-written list when you need to hold and rewire nodes.

Use a singly linked list when

  • You insert or delete at the front often.
  • The size is unknown or changes a lot.
  • You build a stack, a queue or hash-table chains.
  • You hold node references and rewire them (LRU cache, splicing).

Avoid it when

  • You need random access by index.
  • You search or sort a lot.
  • Memory is tight: every node pays for a pointer.
  • The collection is small and fixed: an array is simpler and faster.

Need to walk backwards or delete the tail in O(1)O(1)? Add a prev pointer: that is the doubly linked list. The head-as-top trick also gives you a stack for free.

Recap

Key takeaways

Key points

  • A singly linked list is nodes joined by next pointers, entered through head and ended by None.
  • Insert and delete at the head are O(1)O(1); anything at position kk costs O(k)O(k) to reach, so tail, search and access are O(n)O(n).
  • Insert: link the new node forward first, then rewire. Delete: bypass with prev.next = prev.next.next.
  • Reverse with three pointers: save next, reverse link, advance prev, advance current. Return the new head.
  • Slow and fast pointers find the middle, detect cycles and find the nth node from the end in one pass.
  • A dummy node removes head special cases; a tail pointer makes append O(1)O(1).

Sources