Skip to content

Linked List

Linked List in under a minute

A linked list gives you no indexing: you reach a node only by walking from the head. Almost every problem is solved by moving a couple of pointers and rewiring next links, usually in one pass and O(1) extra space.

  • The input is a singly linked list and you can’t just copy it into an array (or the problem asks for O(1) space).
  • You need the middle, the n-th from the end, or to detect a cycle: use a fast and a slow pointer.
  • You need to reverse all or part of the list: flip pointers in place.
  • You build a new list from old nodes (merge, partition): use a dummy head so the first node is not a special case.
  • The head itself might be removed or replaced: a dummy head fixes that too.
dummy = ListNode(0, head) # 1. dummy head: the real head is never special
slow = fast = dummy # 2. two pointers, different speeds or a fixed gap
while fast and fast.next:
slow, fast = slow.next, fast.next.next
prev, cur = None, head # 3. in-place reversal
while cur:
cur.next, prev, cur = prev, cur, cur.next
return dummy.next # always return dummy.next, not head

Always ask: what if the list is empty, has one node, or the head is the node I change? Save cur.next before you overwrite it, or you lose the rest of the list.