Learn / Linked lists

Traversal and dummy nodes

A linked list is a chain of nodes, each holding a value and a pointer to the next node. You can only walk it from the head, one node at a time. Most changes are "find the node before the spot, then rewire one or two pointers", and a dummy node placed before the head removes the special case of changing the head.

How to recognise it

  • The input is a ListNode head (or several), and the answer is a list, a value, or a node.
  • Nodes must be inserted, deleted, moved or regrouped without copying the values into an array.
  • The head itself might be deleted or replaced.

The idea in one picture

A linked list is a treasure hunt: each clue (node) holds a value and tells you where the next clue is. The head is the first clue, and the last one points to nothing (null).

head →3 →4 →5 →null

You cannot jump to the middle. To reach node k, you follow k - 1 arrows. In exchange, adding or removing a node is just rewiring arrows, with no shifting of other values.

The two moves everything is built from

MoveCodePicture
Delete the node after prevprev.next = prev.next.next3 → 4 → 5 becomes 3 → 5
Insert x after prevx.next = prev.next; prev.next = x3 → 5 becomes 3 → x → 5

Both need the node before the spot. Finding that node is the walk; changing the arrows is O(1).

Template: walk with a dummy node

dummy = new node; dummy.next = head
prev = dummy
while prev.next is not null:
    if prev.next is the node to change:
        rewire around prev.next
        (stop, or keep going without moving prev)
    else:
        prev = prev.next
return dummy.next

With the dummy, the head is just "the node after dummy", so deleting it or inserting before it is not special.

Building new lists from old nodes

Several problems split one list into chains (odd and even positions; 0s, 1s and 2s) and then join the chains. Give each chain its own dummy head and a tail pointer, append nodes to the right tail as you walk, then link the tails together and end the last chain with null.

Common mistakes

  • Losing the rest of the list by overwriting prev.next before saving it.
  • Forgetting to end a rebuilt chain with null, which can leave a cycle.
  • Moving prev forward right after deleting, which skips a node.
  • Returning head when the head itself was deleted. Return dummy.next.
  • Reading node.next.val without checking that node.next exists.

Problems

0 of 18 solved

Check yourself

To delete the node after prev, which single assignment do you need?

Why put a dummy node before the head?

Inserting node x after prev, which order of assignments is correct?

How long does it take to reach the k-th node of a singly linked list?