Linked Lists
How linked lists store data, how to insert, delete and reverse nodes, how fast and slow pointers find the middle or a cycle, and what interviewers ask.
On this page
A linked list is a chain of nodes, where each node holds a value and a reference to the next node. Because nodes are connected by references instead of sitting next to each other in memory, you can insert or remove a node by changing one or two references, without shifting any other data. You reach for a linked list when a problem is about inserting, removing, reordering or splicing items in a sequence, and interview problems use it mainly to test whether you can manipulate pointers without losing part of the list.
An array makes the opposite trade. It reads any position in one step, but inserting at the front moves every other item. A linked list cannot jump to position 1000 without following 1000 references, but inserting next to a node you already hold costs the same for a list of ten items or ten million.
Nodes, the head and pointers
Each node has a value and a field called next. The last node's next is null (None in Python), which marks the end. You keep a reference to the first node, called the head, and reach every other node by following next from there. If you lose the head, you lose the whole list.
To insert a node after a node you hold, the new node takes over the old next and the held node points at the new node. Nothing else moves, as the figure shows.
Traversal follows next from the head until it reaches null. Deletion is the mirror image of insertion: to remove the node after a node you hold, set that node's next to next.next, which skips over the removed node. Both operations need the node before the position you are changing, because a node has no reference back to its predecessor.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function printList(head) {
const parts = [];
for (let node = head; node !== null; node = node.next) parts.push(node.val);
console.log(parts.join(" -> ") + " -> null");
}
function insertAfter(node, val) {
node.next = new ListNode(val, node.next); // new node points where node pointed
}
function deleteAfter(node) {
if (node.next !== null) node.next = node.next.next; // skip over it
}
// Build 4 -> 7 -> 2 -> 5 by adding at the front, last value first.
let head = null;
for (const v of [5, 2, 7, 4]) head = new ListNode(v, head);
insertAfter(head, 9);
printList(head); // 4 -> 9 -> 7 -> 2 -> 5 -> nullclass ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def print_list(head):
parts = []
node = head
while node is not None:
parts.append(str(node.val))
node = node.next
print(" -> ".join(parts) + " -> None")
def insert_after(node, val):
node.next = ListNode(val, node.next) # new node points where node pointed
def delete_after(node):
if node.next is not None:
node.next = node.next.next # skip over it
# Build 4 -> 7 -> 2 -> 5 by adding at the front, last value first.
head = None
for v in [5, 2, 7, 4]:
head = ListNode(v, head)
insert_after(head, 9)
print_list(head) # 4 -> 9 -> 7 -> 2 -> 5 -> NoneThe order of the two assignments in insertAfter matters. The new node must copy node.next before node.next is changed to point at the new node. If you do it the other way round, the rest of the list becomes unreachable.
| Approach | Time | Why |
|---|---|---|
| Read or find the k-th node | O(n) | You follow k references from the head. |
| Insert or delete after a node you hold | O(1) | One or two references change. |
| Insert at the head | O(1) | The new node points at the old head. |
| Search for a value | O(n) | You walk until you find it, or reach the end. |
Reversing a list in place
Reversing turns 4 → 7 → 2 → 5 into 5 → 2 → 7 → 4 by flipping every reference, without building a second list. It is the most common linked list question and the basis for others, such as palindrome checks.
The loop keeps two parts of the list. The part behind you is already reversed, and prev points to its first node. The part ahead is untouched, and current points to its first node. Each round takes the first node of the untouched part and puts it at the front of the reversed part. To do that it saves current.next first, because the next line overwrites it.
prev = nullcurrent = headwhile current != null: next = current.next current.next = prev prev = current current = nextreturn prev- reversed (from prev)nullstill to do (from current)04current172235null
- prev
- null
- current
- 4
1Nothing is reversed yet, so
previs null andcurrentis the head, 4. - reversed (from prev)nullstill to do (from current)04current17next2235null
- prev
- null
- current
- 4
- next
- 7
2The loop first saves
nextas 7, because the next line overwrites4.next. - reversed (from prev)04currentnullstill to do (from current)07next1225null
- prev
- null
- current
- 4
- next
- 7
3It then points node 4 at
prev, which is null. Node 4 is now the start of the reversed chain. - reversed (from prev)04prevnullstill to do (from current)07current1225null
- prev
- 4
- current
- 7
4Both pointers move forward:
prevbecomes 4 andcurrentbecomes the saved 7. - reversed (from prev)07prev14nullstill to do (from current)02current15null
- prev
- 7
- current
- 2
5The round for 7 saves 2, points 7 at 4 and moves both pointers forward.
- reversed (from prev)02prev1724nullstill to do (from current)05currentnull
- prev
- 2
- current
- 5
6The round for 2 saves 5, points 2 at 7 and moves both pointers forward.
- reversed (from prev)05prev122734nullstill to do (from current)null
- prev
- 5
- current
- null
7The round for 5 saves null, points 5 at 2 and moves both pointers forward.
currentis now null, so the loop ends. - result05head122734null
- nodes visited
- 4
- extra memory
- 3 pointers
8The function returns
prev, so the old last node, 5, is the new head.
function reverse(head) {
let prev = null;
let current = head;
while (current !== null) {
const next = current.next; // 1. save the rest of the list
current.next = prev; // 2. flip this node's arrow
prev = current; // 3. step both pointers forward
current = next;
}
return prev; // the old last node is the new head
}def reverse(head):
prev = None
current = head
while current is not None:
nxt = current.next # 1. save the rest of the list
current.next = prev # 2. flip this node's arrow
prev = current # 3. step both pointers forward
current = nxt
return prev # the old last node is the new headEach node is visited once, and only three pointers are kept.
An empty list needs no special case, because the loop body never runs and the function returns null.
Fast and slow pointers
The fast and slow pointer technique answers several questions in one pass: slow moves one node per round and fast moves two. It is the same-direction form of two pointers.
Finding the middle
When fast reaches the end of the list, it has travelled twice as far as slow, so slow is at the halfway point. This avoids counting the nodes first and walking again.
slow = head, fast = headwhile fast != null and fast.next != null: slow = slow.next fast = fast.next.nextreturn slow- list010slow fast120230340450null
- rounds
- 0
1Both pointers start at the head.
- list010fast120slow230340450null
- rounds
- 1
2
fastandfast.nextboth exist, so a round runs.slowmoves one node, to 20. - list010120slow230fast340450null
- rounds
- 1
3
fastmoves two nodes, to 30. - list010120230slow340450fastnull
- rounds
- 2
4In the second round
slowmoves to 30 andfastmoves to 50. - list010120230slow340450fastnull
- rounds
- 2
- middle
- 30
5
fast.nextis null, so the loop ends.slowis on 30, which is the middle.
A list with an even number of nodes has two middle nodes. For 10 → 20 → 30 → 40 → 50 → 60 the loop above returns 40, the second one. To get the first middle, 30, change the condition to fast.next != null and fast.next.next != null and handle the empty list before the loop.
Detecting a cycle
A list has a cycle when some node's next points back to an earlier node. A plain traversal of such a list never ends. With fast and slow pointers, a list without a cycle ends the loop when fast reaches null. In a list with a cycle, both pointers eventually enter it and go around, and they must meet. Once both are inside the cycle, fast gains one node on slow every round, so the distance between them shrinks by exactly one each time and fast cannot jump over slow without landing on it.
slow = head, fast = headwhile fast != null and fast.next != null: slow = slow.next fast = fast.next.next if slow == fast: return truereturn false- rounds
- 0
1The list is 1 → 2 → 3 → 4 → 5 → 6, and node 6 points back to node 3. Both pointers start at 1.
- rounds
- 1
2After round 1,
slowis on 2 andfastis on 3.- rounds
- 2
3After round 2,
slowis on 3 andfastis on 5. Both are now inside the cycle.- rounds
- 3
4In round 3
slowmoves to 4, andfastgoes 5 → 6 → 3, which leaves it one node behindslow.- rounds
- 4
- cycle
- found
5In round 4
slowmoves to 5 andfastgoes 3 → 4 → 5. They are on the same node, which can only happen in a cycle, so the function returns true.
function middle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next; // one step
fast = fast.next.next; // two steps
}
return slow;
}
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true; // fast caught up with slow
}
return false; // fast reached the end of the list
}def middle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next # one step
fast = fast.next.next # two steps
return slow
def has_cycle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast: # fast caught up with slow
return True
return False # fast reached the end of the listSlow enters the cycle within n steps, and fast then closes the gap within another n rounds at most.
Storing visited nodes in a set also detects a cycle in O(n) time, but it uses O(n) memory, which is why interviewers ask for the two-pointer version.
Variants and related techniques
Dummy node
Any change to the first node changes the head, so code that deletes or inserts at the front needs a special case that the rest of the list does not. A dummy node removes that case. You create a node with an unused value, point its next at the real head, work with it as if it were an ordinary predecessor, and return dummy.next at the end. Merging two sorted lists shows the pattern, because you cannot know in advance which list supplies the first node of the result.
function mergeSorted(a, b) {
const dummy = new ListNode(0);
let tail = dummy;
while (a !== null && b !== null) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = a !== null ? a : b; // attach whichever list still has nodes
return dummy.next;
}def merge_sorted(a, b):
dummy = ListNode(0)
tail = dummy
while a is not None and b is not None:
if a.val <= b.val:
tail.next = a
a = a.next
else:
tail.next = b
b = b.next
tail = tail.next
tail.next = a if a is not None else b # attach whichever list still has nodes
return dummy.nextThis relinks the existing nodes and creates no new ones, so it takes O(n + m) time and O(1) extra space for lists of length n and m.
A gap between two pointers
To find the k-th node from the end, you cannot count backwards, because a singly linked list has no way to go back. Instead, move one pointer k nodes ahead, then move both pointers forward one node at a time. When the leading pointer reaches the end, the other pointer is exactly k nodes from the end. To delete that node you need its predecessor, so start both pointers at a dummy node and stop one position earlier. This takes one pass and O(1) space.
Doubly linked lists
In a doubly linked list each node also has a prev reference. You can then delete a node you hold without searching for its predecessor, and you can walk in both directions. The cost is one more reference per node, and one more to update on every insert and delete. A cache that evicts the least recently used item combines a hash map with a doubly linked list. The map finds a node in O(1), and the list moves it to the front or removes it from the back in O(1).
When a linked list is the wrong choice
A linked list cannot do binary search, because that needs a jump to the middle in O(1). Traversal is also slower in practice than for an array, because the nodes are scattered in memory. Use an array unless the problem needs cheap insertion or removal at positions you already hold.
Pitfalls
In the interview
A problem is a linked list problem when its input is a chain of nodes with next references and you are asked to change the order or the contents. The statement usually points to one of these techniques:
- "Reverse", "rotate" or "reorder" a list, or "reverse the nodes in groups of k", means pointer reversal, usually on part of the list.
- "Find the middle", "check for a cycle" or "find where the cycle begins" means fast and slow pointers.
- "Remove the k-th node from the end" means a gap between two pointers, with a dummy node.
- "Merge" or "combine" sorted lists means a dummy node and a tail pointer.
- "Do it in O(1) extra space" or "do it in one pass" rules out copying the list into an array, and points at one of the pointer techniques.
The interviewer is usually watching how carefully you handle the edge cases: an empty list, a single node, deleting the head, and the end of the list. Name them before you code, and run your code on a one-node list and a two-node list when you finish.
These are follow-up questions that interviewers commonly ask on this topic.
- "How do you find the node where the cycle starts?" First run fast and slow until they meet inside the cycle. Then move one pointer back to the head and advance both pointers one node at a time. They meet at the first node of the cycle. This works because the distance from the head to the cycle start equals the distance from the meeting point forward to the cycle start, modulo the cycle length.
- "Why does the fast pointer move by two? Would three work?" With a speed difference of one, the gap shrinks by exactly one per round, so the pointers cannot pass each other without meeting. With a speed of three the gap shrinks by two per round, and in a cycle of even length with an odd gap the pointers can keep jumping past each other and never land on the same node. Two is the speed that always works.
- "Can you reverse the list recursively? What does it cost?" Yes. You reverse the rest of the list recursively, then point the node after the current one back at the current node and set the current node's
nextto null. It takes O(n) time but O(n) stack space, so the iterative version is the better answer for long lists. - "You are given only a pointer to a node in the middle of the list, not the head. How do you delete it?" Copy the value of the next node into the given node, then delete the next node by setting
node.next = node.next.next. This works only when the given node is not the last one, and it changes which node holds which value, which is a problem if other code keeps references to the nodes.
What does it cost to read position k of a linked list with n nodes?
In the reversal loop, what goes wrong if current.next = prev runs before next = current.next?
Fast and slow pointers run on 1 → 2 → 3 → 4 → 5 → 6 → 7, which has no cycle. Which node is slow on when the loop ends?
What to practise next
Practise reversal on Reverse the Playlist, fast and slow pointers on Middle of the Parade, the dummy node on One Van, Two Routes and the pointer gap on Closed Tram Stop. After that, Stacks covers a structure that only touches one end, which a linked list handles well at its head.