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.

20 minLesson 1 of 4
On this page
  1. Nodes, the head and pointers
  2. Reversing a list in place
  3. Fast and slow pointers
  4. Variants and related techniques
  5. Pitfalls
  6. In the interview
  7. What to practise next

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.

Before 4 7 2 5 null After inserting 9 after 4 4 9 7 2 5 null
Inserting 9 after 4 changes two arrows, drawn in the accent color. No other node moves.

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 -> null
class 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 -> None

The 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.

ApproachTimeWhy
Read or find the k-th nodeO(n)You follow k references from the head.
Insert or delete after a node you holdO(1)One or two references change.
Insert at the headO(1)The new node points at the old head.
Search for a valueO(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.

Reverse 4 → 7 → 2 → 5Use the arrows or ← → keys
prev = nullcurrent = headwhile current != null:  next = current.next  current.next = prev  prev = current  current = nextreturn prev
  1. reversed (from prev)
    null
    still to do (from current)
    04current
    17
    22
    35
    null
    prev
    null
    current
    4

    1Nothing is reversed yet, so prev is null and current is the head, 4.

  2. reversed (from prev)
    null
    still to do (from current)
    04current
    17next
    22
    35
    null
    prev
    null
    current
    4
    next
    7

    2The loop first saves next as 7, because the next line overwrites 4.next.

  3. reversed (from prev)
    04current
    null
    still to do (from current)
    07next
    12
    25
    null
    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.

  4. reversed (from prev)
    04prev
    null
    still to do (from current)
    07current
    12
    25
    null
    prev
    4
    current
    7

    4Both pointers move forward: prev becomes 4 and current becomes the saved 7.

  5. reversed (from prev)
    07prev
    14
    null
    still to do (from current)
    02current
    15
    null
    prev
    7
    current
    2

    5The round for 7 saves 2, points 7 at 4 and moves both pointers forward.

  6. reversed (from prev)
    02prev
    17
    24
    null
    still to do (from current)
    05current
    null
    prev
    2
    current
    5

    6The round for 2 saves 5, points 2 at 7 and moves both pointers forward.

  7. reversed (from prev)
    05prev
    12
    27
    34
    null
    still to do (from current)
    null
    prev
    5
    current
    null

    7The round for 5 saves null, points 5 at 2 and moves both pointers forward. current is now null, so the loop ends.

  8. result
    05head
    12
    27
    34
    null
    nodes visited
    4
    extra memory
    3 pointers

    8The function returns prev, so the old last node, 5, is the new head.

1 / 8
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 head
TimeO(n)
SpaceO(1)

Each 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.

Find the middle of 10 → 20 → 30 → 40 → 50Use the arrows or ← → keys
slow = head, fast = headwhile fast != null and fast.next != null:  slow = slow.next  fast = fast.next.nextreturn slow
  1. list
    010slow fast
    120
    230
    340
    450
    null
    rounds
    0

    1Both pointers start at the head.

  2. list
    010fast
    120slow
    230
    340
    450
    null
    rounds
    1

    2fast and fast.next both exist, so a round runs. slow moves one node, to 20.

  3. list
    010
    120slow
    230fast
    340
    450
    null
    rounds
    1

    3fast moves two nodes, to 30.

  4. list
    010
    120
    230slow
    340
    450fast
    null
    rounds
    2

    4In the second round slow moves to 30 and fast moves to 50.

  5. list
    010
    120
    230slow
    340
    450fast
    null
    rounds
    2
    middle
    30

    5fast.next is null, so the loop ends. slow is on 30, which is the middle.

1 / 5

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.

Catch the loop: 6 points back to 3Use the arrows or ← → keys
slow = head, fast = headwhile fast != null and fast.next != null:  slow = slow.next  fast = fast.next.next  if slow == fast: return truereturn false
  1. 1slow, fast23456
    rounds
    0

    1The list is 1 → 2 → 3 → 4 → 5 → 6, and node 6 points back to node 3. Both pointers start at 1.

  2. 12slow3fast456
    rounds
    1

    2After round 1, slow is on 2 and fast is on 3.

  3. 123slow45fast6
    rounds
    2

    3After round 2, slow is on 3 and fast is on 5. Both are now inside the cycle.

  4. 123fast4slow56
    rounds
    3

    4In round 3 slow moves to 4, and fast goes 5 → 6 → 3, which leaves it one node behind slow.

  5. 12345slow, fast6
    rounds
    4
    cycle
    found

    5In round 4 slow moves to 5 and fast goes 3 → 4 → 5. They are on the same node, which can only happen in a cycle, so the function returns true.

1 / 5
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 list
TimeO(n)
SpaceO(1)

Slow 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.

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.next

This 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 next to 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.
Quick check

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.