Skip to content

Lesson 10 of 40Core patterns

Linked Lists

Traverse, reverse and merge linked lists with careful pointer moves, and use fast and slow pointers to find middles and cycles.

18 min read0/5 questions

Linked lists rarely appear in day-to-day application code, but they are an interview favourite because they test one skill directly: can you change pointers in the right order without losing part of your data? The same skill shows up later in trees, graphs and LRU caches. Get comfortable here and those feel easy.

Nodes and pointers

A linked list is a chain of nodes. Each node holds a value and a reference (a pointer) to the next node. The list is known only by its first node, the head. The last node points to None (Python) or null (TypeScript).

Python
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Build 1 -> 2 -> 3head = ListNode(1, ListNode(2, ListNode(3))) node = headwhile node: # stop after the last node print(node.val) node = node.next
Output
Press Run (⌘ Enter) to see what happens.

That while node loop is the traversal every linked list solution starts from. Reaching the k-th node takes k steps, so access by position is O(n). In exchange, inserting or removing a node you already hold is O(1): you just rewire pointers, nothing shifts.

In the practice problems, ListNode is already defined for you in both languages, and lists are passed in and out as heads.

Predict the outputPython

What does this print?

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

head = ListNode(4, ListNode(7, ListNode(9)))
total = 0
node = head
while node.next:
  total += node.val
  node = node.next
print(total)
Need a nudge? Hints walk you through it.

The dummy head

Many list operations have an awkward special case: what if the node you need to change is the head? A dummy (sentinel) node placed before the head removes that case. You build or edit the list after the dummy, then return dummy.next.

def remove_value(head, target):
    dummy = ListNode(0, head)
    prev = dummy
    while prev.next:
        if prev.next.val == target:
            prev.next = prev.next.next   # skip the node
        else:
            prev = prev.next
    return dummy.next                     # works even if the old head was removed
Quick check
Why does remove_value return dummy.next instead of head?
Need a nudge? A hint rules out a wrong answer.

Reversing a list in place

Reversal is the most asked linked list question. Walk the list once and flip each next pointer to point backwards. You need three pointers: prev (the reversed part so far), cur (the node you are flipping), and nxt (saved so you do not lose the rest of the list).

Reversing 1 → 2 → 3
prev, cur = None, head
NamesObjects in memoryprevcurListNode1, next → 2ListNode2, next → 3ListNode3, next → NoneNoneNone

Start: nothing is reversed yet, so prev is None. cur is the head.

1/6
Python
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverse(head): prev, cur = None, head while cur: nxt = cur.next # 1. save the rest cur.next = prev # 2. flip the pointer prev = cur # 3. grow the reversed part cur = nxt # 4. move on return prev def show(node): out = [] while node: out.append(str(node.val)) node = node.next return " -> ".join(out) or "empty" head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))print(show(reverse(head)))print(show(reverse(None)))
Output
Press Run (⌘ Enter) to see what happens.
Put it in order4 steps

Put the four lines of the reversal loop body in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

Reverse a Linked List

You get the head of a singly linked list. Reverse the list so the last node comes first, and return the new head. Do it in place by turning the existing next pointers around, without building a new list.

1 -> 2 -> 3 -> 4 -> 5   becomes   5 -> 4 -> 3 -> 2 -> 1
1 -> 2                 becomes   2 -> 1
(empty)                stays     (empty)

An empty list is None in Python and null in TypeScript.

Constraints

  • 0 <= number of nodes <= 5000
  • -5000 <= Node.val <= 5000
# The harness already defines ListNode:# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = next def reverse_list(head: ListNode | None) -> ListNode | None: # Walk the list once, turning each next pointer around. pass

Fast and slow pointers

Move two pointers through the list at different speeds: slow one step at a time, fast two steps. When fast reaches the end, slow is at the middle.

Finding the middle of 1 → 2 → 3 → 4 → 5
1
0
↑slow↑fast
2
1
3
2
4
3
5
4

Both start at the head.

1/4
slow = fast = head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
# slow is the middle (the second middle for even lengths)
Quick check
With the loop above on 1 → 2 → 3 → 4, where does slow end?
Need a nudge? A hint rules out a wrong answer.

Cycle detection (Floyd's algorithm). If a list has a cycle, the last node points back to an earlier one and a normal traversal never ends. Run the same fast and slow pointers: in a cycle, fast gains one step on slow every round, so it must eventually land on the same node. If fast reaches None instead, there is no cycle. That is O(n) time and O(1) space, versus O(n) space for a "seen" set of nodes.

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:          # same node object, not just equal values
            return True
    return False

Practice it with the linked-list-cycle problem. The same pair of pointers also finds the k-th node from the end: start fast k steps ahead, then move both until fast hits the end.

Merging two sorted lists

To merge two sorted lists into one, keep a tail pointer starting at a dummy node. Repeatedly attach the smaller of the two front nodes to tail, advance that list, and advance tail. When one list runs out, attach the rest of the other in one step.

def merge(a, b):
    dummy = tail = ListNode()
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b           # attach whatever is left
    return dummy.next

It reuses the existing nodes, so it is O(n + m) time and O(1) extra space.

ChallengeEasy

Merge Two Sorted Lists

You get the heads of two linked lists, a and b, each already sorted in ascending order. Splice them together into one sorted list and return its head. Reuse the existing nodes rather than making new ones.

a = 1 -> 2 -> 4,  b = 1 -> 3 -> 4   →  1 -> 1 -> 2 -> 3 -> 4 -> 4
a = (empty),      b = 0             →  0
a = (empty),      b = (empty)       →  (empty)

If both are empty, return None (null in TypeScript).

Constraints

  • 0 <= number of nodes in each list <= 50
  • -100 <= Node.val <= 100
  • Both lists are sorted in non-decreasing order.
# The harness already defines ListNode:# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = next def merge_two_lists(a: ListNode | None, b: ListNode | None) -> ListNode | None: # Repeatedly take the smaller front node from a or b. pass

Complexity and common mistakes

OperationTimeExtra space
Traverse, find, find middleO(n)O(1)
Insert or delete after a node you holdO(1)O(1)
Reverse in placeO(n)O(1)
Merge two sorted listsO(n + m)O(1)
Cycle detection (Floyd)O(n)O(1)
  • Losing the rest of the list by overwriting cur.next before saving it.
  • Not handling None/null: an empty list, a one-node list, or calling .next on None. Check fast and fast.next before fast.next.next.
  • Returning the old head after the head changed. Return dummy.next or prev.
  • Comparing values instead of nodes in cycle detection. Use is in Python and === in TypeScript.
Match the pairs0/4 matched

Which technique fits?

Choose an item, then its match on the other side.
Key terms
node
One element of a linked list: a value plus a pointer to the next node.
head
The first node. The whole list is reached from it.
dummy head
A placeholder node before the real head that removes special cases; return dummy.next.
in-place reversal
Flip each next pointer using prev, cur and nxt. O(n) time, O(1) space.
fast and slow pointers
Two pointers moving at speeds 2 and 1. Finds the middle, cycles, and k-th from the end.
Floyd's algorithm
Cycle detection: if fast and slow ever meet, the list has a cycle.
Interview pattern: Linked List31 problemsSpot it: Reverse · merge · find the middle · detect a cycle