Skip to content
Lesson 7 of 10 · Coding Interview Prep: Data Structures and Algorithms

Linked lists

Work with nodes and pointers: reverse a list and find its middle with the slow and fast pointer trick.

24 min

A linked list is a chain of nodes. Each node holds a value and a reference (next) to the following node; the last one points to None. You hold only the head, the first node.

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

1 → 2 → 3 is ListNode(1, ListNode(2, ListNode(3))).

OperationArray (Python list)Linked list
Read item iO(1)O(i): walk from the head
Insert or delete after a known nodeO(n) shiftO(1): rewire pointers
Insert at the frontO(n)O(1)

Interviews love linked lists because they test careful thinking about pointers. Pictures help: draw boxes and arrows.

python4 lines
node = head
while node:
    print(node.val)
    node = node.next

Reverse by flipping each arrow as you walk. Keep three things: where you came from (prev), where you are (cur), and where you were going (nxt), which you must save before you overwrite cur.next:

python7 lines
prev, cur = None, head
while cur:
    nxt = cur.next      # 1. remember the rest
    cur.next = prev     # 2. flip the arrow
    prev = cur          # 3. step forward
    cur = nxt
return prev             # the new head

O(n) time, O(1) space.

Move slow one step and fast two steps at a time. When fast reaches the end, slow is at the middle. The same trick detects a cycle: if there is a loop, fast eventually laps slow and they meet.

An empty list (head is None), a single node, two nodes, and, for deletion, removing the head. A dummy node placed before the head removes most of the special cases.

Before reversing: 1, 2, 3. After: the arrows flip and 3 becomes the head.

Exercise5 checks
python

Write reverse_list(head) that reverses the linked list and returns the new head. Use O(1) extra space. The helpers from_list and to_list are given for building and reading lists; leave them as they are.

to_list(reverse_list(from_list([1, 2, 3]))) is [3, 2, 1].

Your code must satisfy

  • to_list(reverse_list(from_list([1, 2, 3])))→[3,2,1]three nodes
  • to_list(reverse_list(from_list([])))→[]empty
  • to_list(reverse_list(from_list([7])))→[7]one node
  • to_list(reverse_list(from_list([1, 2])))→[2,1]two nodes
  • to_list(reverse_list(from_list([5, 4, 3, 2, 1])))→[1,2,3,4,5]five nodes
starter code23 lines
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def from_list(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out


def reverse_list(head):
    pass
Exercise6 checks
python

Write middle_value(head) returning the value in the middle node of a non-empty list. For an even number of nodes, return the second of the two middle values (so [1, 2, 3, 4] gives 3). Make one pass using a slow and a fast pointer. For an empty list return -1.

Your code must satisfy

  • middle_value(from_list([1, 2, 3]))→2odd
  • middle_value(from_list([1, 2, 3, 4]))→3even
  • middle_value(from_list([9]))→9single
  • middle_value(from_list([5, 6]))→6two
  • middle_value(from_list([]))→-1empty
  • middle_value(from_list([10, 20, 30, 40, 50]))→30five
starter code15 lines
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def from_list(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def middle_value(head):
    pass
Common misconception

“Reversing a list just means changing the order of the values.”

With a Python list, reversing is exactly that.

What is actually true

In a linked list you change the arrows, not the values. If you overwrite cur.next before saving it, you lose the rest of the list.

How to catch yourself

Say it as a rule: "save next, flip, step."

  • A linked list is nodes with val and next; you hold the head.
  • Reaching item i costs O(i), but inserting or deleting after a known node is O(1).
  • Reverse with prev, cur and a saved next; slow and fast pointers find the middle or a cycle.
  • Check empty, one-node and two-node lists, and use a dummy node to simplify deletion.
Check yourself

Pointer checks.

1Multiple choice

What does the last node's next hold?

  • AThe head
  • B`None`
  • C0
  • DItself
2Multiple choice

Why save nxt = cur.next before cur.next = prev?

  • APython requires it
  • BOtherwise you lose the rest of the list
  • CIt is faster
  • DTo avoid recursion
3Multiple choice

When fast reaches the end of a 5-node list, which node is slow on?

  • AThe 2nd
  • BThe 3rd
  • CThe 4th
  • DThe 1st
4Multiple choice

Which is O(1) in a linked list, given the node?

  • AReading the 100th item
  • BInserting a new node right after it
  • CSorting
  • DFinding the length
5Fill the blanks

The first node of a linked list is called the .

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.