DSA/Lesson 3 of 11/5 min read
Linked Lists
Singly, doubly and circular linked lists, fast and slow pointers, reversal, cycle detection and classic interview problems.
On this page
Linked List
A linked list is a sequence of nodes where each node stores a value and a pointer to the next node. Nodes live anywhere in memory, so there is no random access.
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = nextLinked list vs array
| Operation | Array | Linked list |
|---|---|---|
| Access i-th | O(1) | O(n) |
| Insert / delete at head | O(n) | O(1) |
| Insert / delete after known node | O(n) | O(1) |
| Memory | Compact | Extra pointer per node |
| Cache locality | Excellent | Poor |
Use a linked list when you need frequent insertions and deletions in the middle given a node reference, or as a building block (hash table chaining, LRU cache, adjacency lists).
Singly Linked List
Each node points only to the next. The last node points to null. You need the previous node to delete a node, so deletion is usually done by tracking prev.
Reversing a list
The single most asked linked list question.
def reverse(head):
prev = None
cur = head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prevO(n) time, O(1) space. The recursive version uses O(n) stack space.
Doubly Linked List
Each node has prev and next. Deleting a node given only its reference is O(1) because you can reach its predecessor. Costs one extra pointer per node. Used by Java LinkedList, browser history, and LRU caches.
Circular Linked List
The last node points back to the head. Useful for round-robin scheduling and circular buffers. Pitfall: a naive while node: loop never ends; stop when you return to the head.
Sentinel Node
A dummy node placed before the head removes special cases for an empty list or for operations that change the head.
def remove_value(head, target):
dummy = ListNode(0, head)
prev = dummy
while prev.next:
if prev.next.val == target:
prev.next = prev.next.next
else:
prev = prev.next
return dummy.nextMerging two sorted lists, partitioning and removing nodes all get simpler with a dummy head.
Fast and Slow Pointers
Move slow one step and fast two steps.
Middle of the list
When fast reaches the end, slow is at the middle. Used in merge sort on lists and palindrome checks.
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowNth node from the end
Advance fast by n first, then move both until fast hits the end. One pass.
Floyd's Cycle Detection
Also called the tortoise and hare algorithm. If there is a cycle, fast eventually laps slow and they meet. O(n) time, O(1) space (vs O(n) space for a visited set).
Finding the cycle start: after they meet, reset one pointer to the head and move both one step at a time. They meet at the start of the cycle.
Why it works: if the distance from head to cycle start is a and the meeting point is b into the cycle of length c, then 2(a + b) = a + b + kc, so a = kc - b. Walking a steps from the meeting point lands on the cycle start.
Classic problems
| Problem | Technique |
|---|---|
| Merge two sorted lists | Dummy head, compare and splice |
| Palindrome linked list | Find middle, reverse second half, compare |
| Intersection of two lists | Two pointers switch heads at end; meet at intersection |
| Remove nth from end | Fast pointer ahead by n |
| Reorder list (L0, Ln, L1, Ln-1 ...) | Middle, reverse, merge alternately |
| Copy list with random pointer | Hash map old to new, or interleave nodes |
| Merge k sorted lists | Min-heap, O(N log k) |
LRU Cache
Least Recently Used cache with O(1) get and put. Combine:
- a hash map from key to node, for
O(1)lookup; - a doubly linked list ordered by recency, for
O(1)move-to-front and evict-from-tail.
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.map = {}
self.head = ListNode(0) # sentinels
self.tail = ListNode(0)
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _add_front(self, node):
node.next, node.prev = self.head.next, self.head
self.head.next.prev = node
self.head.next = nodeOn get: move the node to the front. On put: insert at front; if over capacity, remove tail.prev and delete its key from the map. In Python, OrderedDict with move_to_end does this for you.
Pitfalls
- Losing the rest of the list by overwriting
nextbefore saving it. - Null pointer errors on
fast.next.next: always checkfast and fast.next. - Forgetting to update the head when the first node changes (use a dummy).
- Memory leaks in C/C++ when deleting nodes.
Quick revision
- No random access;
O(1)insert and delete at a known position. - Reverse with
prev,cur,nxt. - Dummy sentinel removes head edge cases.
- Fast and slow pointers find the middle and detect cycles.
- Floyd: after meeting, reset one pointer to head; they meet at the cycle start.
- LRU cache = hash map + doubly linked list.