Singly linked list
easy 18 minA 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
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.
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
nextpointer.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
next points at the following node, and the last one points at NULL.| Part | What it holds | Why it matters |
|---|---|---|
val | The data | What you store and search for |
next | A reference to the next node, or None | The only link to the rest of the list |
head | A reference to the first node | Lose it and every node becomes unreachable |
NULL (None) | The end marker | Every loop stops when current becomes None |
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) # NoneMemory
Scattered nodes versus a contiguous array
An array keeps its elements in one block, so the computer can calculate where element lives. A linked list's nodes can be anywhere on the heap, so the only way to find node is to follow pointers from the head.
Calculate versus follow
The price of the pointer
Insert
Inserting at the head, the tail or a position
| Where | Pointer changes | Cost | On 10 → 20 → 30 |
|---|---|---|---|
| Head | new.next = head, then head = new | insert 5: 5 → 10 → 20 → 30 | |
| Tail | walk to the last node, then last.next = new | , with a tail pointer | insert 40: 10 → 20 → 30 → 40 |
| Position | walk steps, new.next = cur.next, cur.next = new | insert 25 at 2: 10 → 20 → 25 → 30 |
insert_at(k, x)
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)
Cheap deletes
- Delete head: one assignment, .
- Delete the node after one you already hold: .
- No elements shift, unlike an array.
Expensive deletes
- Delete tail: walk to the second-to-last node, .
- Delete by value or by position: walk to find it first, .
- You need the node before the target, which a singly list cannot step back to.
Walk
Traversal and search
search(target)
Average cost of a successful search
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)) # -1Complexity
What each operation costs
| Operation | Time | Space | Why |
|---|---|---|---|
| Insert at head | Two pointer assignments | ||
| Insert at tail | Walk to the last node; if you keep a tail pointer | ||
| Insert at position | Walk nodes first | ||
| Delete head | Move head to head.next | ||
| Delete tail | Must find the second-to-last node | ||
| Search, access by index | No random access | ||
| Reverse (iterative) | Visit each node once, three pointers | ||
| The list itself | One node per element, each with a pointer |
Linked list wins
- Insert at the head: versus shifting.
- Delete at the head: .
- Never reallocates or copies when it grows.
- Splicing two lists is a pointer change.
Array wins
- Access by index: versus .
- Binary search on sorted data.
- Cache-friendly, contiguous memory.
- Less memory: no pointer per element.
Classic
Reversing a list in place
Iterative reverse
current falls off the end, prev is the old tail and the new head.The four moves, every lap
- 1
Save next
next_node = current.next, before anything is overwritten. - 2
Reverse the link
current.next = prevpoints this node backwards. - 3
Advance prev
prev = current: the reversed part now starts here. - 4
Advance current
current = next_node, using the saved reference.
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]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
Floyd's cycle detection
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.
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]Dummy node
Handles the empty list, head deletes and merges with one code path. Return
dummy.next.Tail pointer
Makes append , which is how a linked-list queue works. Delete tail stays .
Size counter
Update it on every insert and delete to answer
len()in instead of walking.
Choosing
Linked list or array?
Array or linked list?
collections.deque already gives 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 ? 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
nextpointers, entered throughheadand ended byNone. - Insert and delete at the head are ; anything at position costs to reach, so tail, search and access are .
- 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 .