Linked Lists
Nodes connected by pointers — O(1) insertion anywhere you already are, at the price of O(n) access.
A linked list stores elements in separate nodes, each holding a value and a pointer (reference) to the next node. Nodes can live anywhere in memory — the pointers stitch them into a sequence.
Arrays vs linked lists
- Contiguous memory
- O(1) access by index
- O(n) insert/delete in middle (shifting)
- Excellent cache locality
- Fixed size or amortized resizing
- Scattered nodes + pointers
- O(n) access by index (must walk)
- O(1) insert/delete given the node
- Poor cache locality (pointer chasing)
- Grows one node at a time; extra memory per node for pointers
Variants
- Singly linked —
nextonly. Minimal memory; can only move forward. - Doubly linked —
prevandnext. O(1) removal of a known node and backward traversal. Java'sLinkedList, the LRU cache. - Circular — the tail points back to the head. Round-robin schedulers, ring buffers.
Implementation
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
class LinkedList {
private ListNode head;
private int size;
void addFirst(int val) { // O(1)
ListNode n = new ListNode(val);
n.next = head;
head = n;
size++;
}
void addLast(int val) { // O(n) without a tail pointer
ListNode n = new ListNode(val);
if (head == null) { head = n; size++; return; }
ListNode cur = head;
while (cur.next != null) cur = cur.next;
cur.next = n;
size++;
}
boolean remove(int val) { // O(n): find, then unlink
ListNode dummy = new ListNode(0);
dummy.next = head;
for (ListNode prev = dummy; prev.next != null; prev = prev.next) {
if (prev.next.val == val) {
prev.next = prev.next.next; // unlink
head = dummy.next;
size--;
return true;
}
}
return false;
}
}class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def add_first(self, val): # O(1)
self.head = ListNode(val, self.head)
self.size += 1
def add_last(self, val): # O(n) without a tail pointer
node = ListNode(val)
if not self.head:
self.head = node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = node
self.size += 1
def remove(self, val) -> bool: # O(n)
dummy = ListNode(0, self.head)
prev = dummy
while prev.next:
if prev.next.val == val:
prev.next = prev.next.next
self.head = dummy.next
self.size -= 1
return True
prev = prev.next
return Falseclass ListNode {
constructor(public val: number, public next: ListNode | null = null) {}
}
class LinkedList {
head: ListNode | null = null;
size = 0;
addFirst(val: number) { // O(1)
this.head = new ListNode(val, this.head);
this.size++;
}
addLast(val: number) { // O(n) without a tail pointer
const node = new ListNode(val);
if (!this.head) this.head = node;
else {
let cur = this.head;
while (cur.next) cur = cur.next;
cur.next = node;
}
this.size++;
}
remove(val: number): boolean { // O(n)
const dummy = new ListNode(0, this.head);
for (let prev = dummy; prev.next; prev = prev.next) {
if (prev.next.val === val) {
prev.next = prev.next.next;
this.head = dummy.next;
this.size--;
return true;
}
}
return false;
}
}Complexity
| Operation | Singly | Doubly (with tail) |
|---|---|---|
| Access i-th | O(n) | O(n) |
| Insert at head | O(1) | O(1) |
| Insert at tail | O(n) / O(1) with tail | O(1) |
| Delete given node | O(n) (need prev) | O(1) |
| Search | O(n) | O(n) |
Classic techniques
- Linked lists trade O(1) indexing for O(1) splicing at a known node.
- Doubly linked lists allow O(1) deletion of a known node — the basis of LRU caches.
- Use a dummy head to eliminate edge cases; draw the pointers before coding.
- In practice arrays usually win because of cache locality.
QDetect whether a linked list has a cycle.easy
Floyd's tortoise and hare: slow moves 1 step, fast moves 2. If they ever meet there's a cycle; if fast reaches null there isn't. O(n) time, O(1) space. To find the cycle start, reset one pointer to head and move both 1 step until they meet.
QFind the middle node in one pass.easy
Fast/slow pointers again: when fast reaches the end, slow is at the middle.
QRemove the n-th node from the end in one pass.medium
Advance fast n steps, then move fast and slow together until fast.next is null; slow.next is the node to delete. Start both at a dummy node so deleting the head works.
QHow would you delete a node when you're only given that node (not the head)?medium
Copy the next node's value into it and unlink the next node: node.val = node.next.val; node.next = node.next.next. Doesn't work for the tail.