Linked Lists

Data Structures & Algorithms · Linked Lists, Stacks & Queues · Intermediate · 12 min

A chain of nodes where each one points to the next.

A row of boxes joined by arrows, ending in None. First, three sticky notes, prev, curr and nxt, hop along the row and turn every arrow around behind them. Then two runners race along it: fast jumps two boxes for every one box slow takes, so when fast runs off the end, slow is standing on the middle box.

The idea in everyday words

A treasure hunt: each clue tells you where the next clue is. You can't jump to clue #5 directly: you must follow the chain from the start. But adding a new clue in the middle is easy: just change one pointer.

Node = value + next

[1] → [2] → [3] → None

  • Access by position: O(n) (follow the chain)
  • Insert/delete when you're already at the spot: O(1)

Fast & slow pointers

Move slow 1 step and fast 2 steps. When fast reaches the end, slow is in the middle. If fast ever meets slow, there's a cycle. (Like a runner lapping a walker on a circular track.)

Step by step

  1. Reverse: start:

    Technique 1, reversing 1→2→3→None. prev = None, curr = 1.

  2. Flip 1 and 2:

    Save nxt = curr.next, point curr.next back at prev, then step: prev = curr, curr = nxt. After node 1: None←1, then None←1←2.

  3. Flip 3, done:

    None←1←2←3. curr is None, so stop. prev (node 3) is the new head.

  4. Middle: start:

    Technique 2 (this lesson's challenge), finding the middle of 1→2→3→4→5. slow = 1, fast = 1.

  5. Step:

    slow moves 1, fast moves 2: slow = 2, fast = 3.

  6. Step:

    slow = 3, fast = 5.

  7. fast at end:

    fast has no node after it, so stop. slow = 3 is the middle!

Code example

class Node:
    def __init__(self, val, next=None):
        self.val, self.next = val, next

def reverse(head):
    prev = None
    while head:
        nxt = head.next     # save
        head.next = prev    # flip arrow
        prev, head = head, nxt
    return prev

head = Node(1, Node(2, Node(3)))
node = reverse(head)
while node:
    print(node.val, end=" -> ")
    node = node.next
print("None")

Complexity

  • Time: O(n)
  • Space: O(1)

Interview tips

  • Reverse a linked list is asked VERY often: practice until automatic.

  • Mention dummy nodes when merging lists.

  • Floyd's cycle detection = fast/slow pointers.

Challenge: Find the Middle

A linked list is given as a plain list of values (to keep things simple). Using the fast & slow pointer idea with indexes, return the middle value. If there are two middles, return the second one.

Example: middle_value([1,2,3,4,5]) → 3, middle_value([1,2,3,4]) → 3

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Linked Lists, Stacks & Queues

Previous: 2D Grids & Matrix Traversal · Next: Stacks & Queues