Linked Lists and Pointer Operations
A linked list keeps order with links between nodes instead of positions in memory. Changing a few links is cheap; reaching a node means walking to it. Every operation is a walk followed by a few careful pointer writes.
Nodes, and What Holds Them Together
A linked list stores each value in its own node. A node holds the value and at least one pointer, the address of another node. The nodes can sit anywhere in memory, in any order; the pointers alone decide which value comes next.
The list is reached through one head reference, and the last node points to null. There is no stored position and often no stored length. To get anywhere you start at head and follow links, one node at a time.
That is the whole linked list data structure, and one fact follows from it: there is no address arithmetic. An array can compute where element k lives. A list has to walk there. Every cost difference later in this lesson comes back to that.
- Node = value + pointer to another node
headis the only way in; lose it and the list is gonenullmarks the end; there is usually no stored length
Linked List Operations and Their Cost
The main linked list operations are traverse, search, insert and delete. Each is split into two parts: reach the right node, which is a walk, then change the links, which is a few writes. The walk is O(n) unless you already hold the node; the rewiring is O(1).
So inserting or deleting at the head is O(1), and so is inserting after a node you already hold. Anything by position, search by value or reading the k-th value walks first and costs O(n). Appending at the tail is O(n) too, unless the list keeps a tail pointer, which makes it O(1).
- Traverse:
while node: ...; node = node.next - Insert after p:
x.next = p.next, thenp.next = x - Delete after p:
p.next = p.next.next - Keep a tail pointer when you append often
Linked List vs Array
The choice between a linked list and an array comes down to one sentence: an array is faster to read by position, a linked list is faster to edit once you are already at the spot.
Inserting into the middle of an array shifts every later value one slot along. A list changes two links and no value moves. But reaching the middle costs O(n) hops in a list and nothing in an array. So inserting at position k from scratch is O(n) for both: the array pays in shifting, the list in walking.
Two costs hide behind the O-notation. Array slots sit side by side, so the CPU loads them ahead of time and a scan is very fast. List nodes are scattered, so each hop can miss the cache. And each node carries a pointer: a list of 4-byte integers spends 8 more bytes per node on the link, at least two thirds of its memory. This is why std::vector and Python's list (an array) are the usual defaults, and a linked list is chosen for a reason.
| Task | Array | Linked list |
|---|---|---|
| Read the k-th value | O(1) | O(n) |
| Insert or delete at the front | O(n) | O(1) |
| Insert or delete at a held node | O(n) shifting | O(1) |
| Grow | Copy to a bigger block | One node at a time |
| Scan speed in practice | Fast, cache-friendly | Slower, scattered |
- Reading by position: array
- Frequent edits at the ends or at held nodes: linked list
- Pointer overhead and cache misses often decide it in practice
Terms, operations, and practical uses
Parts of a list
- NodeOne allocation holding a value and the link (or links) to its neighbours.
- HeadThe reference to the first node; the only way into the list.
- TailThe last node. Its
nextisnullunless the list is circular. - Dummy nodeA placeholder before the real head, so inserting or deleting at the front needs no special case.
Pointer moves
- HopFollowing one
nextlink. Reaching position k costs k hops. - RewireChanging one link. Insert after a node needs two; delete after a node needs one.
- Orphaned nodeA node no link reaches any more, usually because a link was overwritten before it was saved.
Costs to remember
- O(1) at a held nodeInsert or delete next to a node you already have, with no walk.
- O(n) by positionReading, inserting or deleting at index k first walks k nodes.
- Pointer overheadEach node stores at least one address, 8 bytes on a 64-bit machine.
Code in Python, C++ and Java
def reverse(head):
previous = None
current = head
while current:
following = current.next
current.next = previous
previous = current
current = following
return previous
class Node:
def __init__(self, value, next=None):
self.value, self.next = value, next
head = Node(10, Node(20, Node(30)))
node = reverse(head)
parts = []
while node:
parts.append(str(node.value))
node = node.next
print(' → '.join(parts) + ' → null')#include <iostream>
#include <string>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* previous = nullptr;
ListNode* current = head;
while (current != nullptr) {
ListNode* following = current->next;
current->next = previous;
previous = current;
current = following;
}
return previous;
}
int main() {
ListNode* head = new ListNode(10, new ListNode(20, new ListNode(30)));
ListNode* node = reverseList(head);
string out;
while(node) {
out += to_string(node->val) + " \u2192 ";
node = node->next;
}
cout << out << "null\n";
}public class Main {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
ListNode reverseList(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
ListNode following = current.next;
current.next = previous;
previous = current;
current = following;
}
return previous;
}
public static void main(String[] args) {
ListNode head = new ListNode(10, new ListNode(20, new ListNode(30)));
ListNode node = new Main().reverseList(head);
StringBuilder sb = new StringBuilder();
while(node != null) {
sb.append(node.val).append(" \u2192 ");
node = node.next;
}
System.out.println(sb + "null");
}
}Step through it
Running on 10 20 30 40 50; insert 25 after 20, delete 40, insert 5 at the front, read the 5th value
Types of Linked List
The types of linked list differ in two ways: how many links each node has, and whether the last node points to null or back to the start.
A singly linked list has next only. It is the smallest and moves forward only. A doubly linked list adds prev, which buys backward movement and O(1) deletion of a node you hold, since the node can find its own predecessor. A circular linked list points the last node back to the first, so there is no null to stop on; a circular doubly list wraps both ways.
Pick by the operation that must be cheap. Forward-only scans: singly. Removing nodes you already hold, as in an LRU cache: doubly. Endless rotation over a fixed set, as in round-robin scheduling: circular. C++'s std::list and the Linux kernel's list_head are circular doubly lists with a sentinel node; Java's LinkedList is doubly linked with null ends.
- Singly: one link, forward only
- Doubly:
prevtoo, O(1) delete of a held node - Circular: no
null; stop when you reach the start again - Circular doubly: wraps both ways
Rewiring Without Losing Nodes
Almost every linked-list bug is a pointer write done one step too early. The rule: save the link you are about to overwrite, before you overwrite it.
Inserting x after p is x.next = p.next, then p.next = x. Swap the two lines and p.next already points to x when you read it, so x points to itself and every node after p is unreachable. In C that is a memory leak; in Python or Java the nodes are silently gone.
Deletion works through the node before the one you remove, because that node holds the link to change. Three cases need their own check every time: the empty list, a list of one node, and any change at the head. A dummy node placed before the real head gives every real node a predecessor, so the head case uses the same code as the middle.
- New node's link first, incoming link second
- Delete by rewiring the predecessor
- A dummy head removes the head special case
Where Linked Lists Are Used
Linked lists suit work that adds and removes at known places and rarely needs the k-th item. Stacks and queues can be built from them with O(1) push and pop and no resizing. An LRU cache pairs a hash map with a doubly linked list so it can move a used entry to the front in O(1). Hash tables with chaining keep each bucket as a short list. Operating systems link free memory blocks and ready processes the same way.
Many interview problems are about the links themselves: reversing, merging two sorted lists, finding the middle, detecting a loop. The last two use two pointers moving at different speeds, covered in fast and slow pointers.
- Stacks, queues, LRU caches, hash-table buckets
- OS free lists and run queues
- Interview staples: reverse, merge, middle, cycle