1 · Linked ListsLinked List Basics
All courses

Train cars, not arrays — you only get the next coupling.

A linked list is nodes that only know their next. No nums[i] jump. You start at head and walk until None, like checking couplings on a train.

head → … → null 1 2 3 4 null

Tiny example: list 1 → 2 → 3 → 4. You want a normal Python list of values. Start a pointer at the head, append cur.val, then cur = cur.next. When cur is None, you’re done.

Dry run

  1. head points at 1. out = [], cur = head.
  2. Append 1 → [1]. Move to 2.
  3. Append 2 → [1, 2]. Move to 3.
  4. Append 3 → [1, 2, 3]. Move to 4.
  5. Append 4 → [1, 2, 3, 4]. cur.next is None — loop ends.

Complexity

Time: O(n) — one visit per node. Space: O(1) extra if you only print; O(n) if you build a new list (the output itself).

Common mistakes

  • Forgetting to advance cur = cur.next → infinite loop on a live node.
  • Starting at head.next and dropping the first value.
  • Returning early when you hit the last node instead of when cur becomes None.
Tip: Draw boxes and arrows on paper once. Most “pointer bugs” are just skipped drawings.

Your turn: implement traverse. Expected output: [1, 2, 3, 4].

Watch it run

Train cars: 1 → 2 → 3 → 4

1 / 7

Singly linked list: each node points to the next.

1 2 3 4
Output
Press Run to execute your code.