Skip to content
dsa/roadmap
← All cheat sheets
04

Linked Lists

dsa.fetehadin.com
4.1 Pointers, new/delete & the Heap

A pointer holds an address. new asks the heap for memory that lives until you delete it. Master this and linked lists become easy.

&x, *p, p->fieldO(1)
new / delete one objectO(1) (amortised; done by the allocator)
Stack memoryautomatic: freed when the function returns
Heap memorymanual: lives until delete
  • ✗Dereferencing nullptr or an uninitialised pointer, which crashes (segmentation fault).
  • ✗Using memory after delete (dangling pointer). Set the pointer to nullptr right after.
  • ✗new[] paired with delete instead of delete[].
4.2 Singly Linked List

Nodes on the heap, each pointing to the next. Insert at front, end or a position, delete by value, search and traverse, plus the dummy-node trick and the classic pitfalls.

Insert at frontO(1)
Insert at endO(n), or O(1) with a tail pointer
Insert at position kO(k)
Delete by value / searchO(n)
Access the i-th itemO(n): no random access
SpaceO(n) plus one pointer per node
  • ✗Losing the list by updating head before linking the new node (head = n; first).
  • ✗Dereferencing temp->next without checking temp != nullptr.
  • ✗Forgetting the empty-list and delete-the-head special cases.
4.3 Doubly Linked List

Each node points both forward and backward. You can walk in both directions and delete a node knowing only its address, at the cost of one extra pointer per node.

Insert / delete at front or end (with tail)O(1)
Delete a node you already have a pointer toO(1): no need to find prev
Search / delete by valueO(n)
Traverse backwardO(n): impossible in a singly list without extra memory
SpaceO(n), with 2 pointers per node
  • ✗Updating next but forgetting prev (or the reverse). Each insert or delete touches both directions.
  • ✗Forgetting cur->next->prev when cur->next is nullptr (deleting the tail) → crash.
  • ✗Not updating tail when deleting the last node.
Pointer:
A variable that stores a memory address.
Heap (memory):
Memory for dynamic allocation with new/delete. Lives until you free it.
Memory leak:
Heap memory that is no longer reachable but was never deleted.
Dangling pointer:
A pointer to memory that has already been freed.
Node:
One element of a linked structure: data plus pointer(s) to other nodes.
Head:
Pointer to the first node of a linked list.
Dummy (sentinel) node:
A fake node placed before the head so every real node has a predecessor.
Doubly linked list:
Each node has both next and prev pointers, allowing backward traversal and O(1) delete given a node.

Keyboard shortcuts

⌘K /
Search topics, glossary, cheat sheets
space
Play / pause the visualizer
← →
Step back / forward
r
Reset the visualizer
?
Show this help